package com.mrjy.payment.bo;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alipay.util.AlipayNotify;
import com.mrjy.activity.dao.IActivityInfoDao;
import com.mrjy.activity.dao.IActivitySignupInfoDao;
import com.mrjy.common.dto.BalanceRechargeDto;
import com.mrjy.common.dto.OrderListDto;
import com.mrjy.common.dto.SMSSendDto;
import com.mrjy.common.entity.ActivityInfo;
import com.mrjy.common.entity.ActivitySignupInfo;
import com.mrjy.common.entity.CoursePackageInfo;
import com.mrjy.common.entity.CoursePackageVip;
import com.mrjy.common.entity.DistributorInfo;
import com.mrjy.common.entity.HappinessInfo;
import com.mrjy.common.entity.IntegralExchange;
import com.mrjy.common.entity.IntegralExchangedLog;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.OrderInfo;
import com.mrjy.common.entity.OrderStatusInfo;
import com.mrjy.common.entity.PromoteDetail;
import com.mrjy.common.entity.QuestionComment;
import com.mrjy.common.entity.QuestionInfo;
import com.mrjy.common.entity.RecordIncomeInfo;
import com.mrjy.common.entity.SMSSendInfo;
import com.mrjy.common.entity.SMSSendReqInfo;
import com.mrjy.common.entity.TeacherInfo;
import com.mrjy.common.entity.TransferInfo;
import com.mrjy.common.entity.UserBalanceInfo;
import com.mrjy.common.entity.UserBalancePayment;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.entity.VideoVip;
import com.mrjy.common.entity.VipPackageInfo;
import com.mrjy.common.entity.WechatSMSInfo;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.util.CharSetUtil;
import com.mrjy.common.util.ConstantsUtil;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.ExportExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.OrderCodeUtil;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.ResponseCode;
import com.mrjy.common.util.SMSTemplate;
import com.mrjy.common.util.SMSUtil;
import com.mrjy.coursepackage.dao.ICoursePackageInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.coursepackage.dto.CoursePackageInfoDTO;
import com.mrjy.integral.dao.IHappinessInfoDao;
import com.mrjy.integral.dao.IIntegralExchangeDao;
import com.mrjy.integral.dao.IIntegralExchangedLogDao;
import com.mrjy.integral.util.HappinessInfoEnum;
import com.mrjy.integral.util.HappinessInfoUtil;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.bo.ISMSSendInfoBo;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IPartnerInfoDao;
import com.mrjy.maintain.dao.IPromoteDetailDao;
import com.mrjy.maintain.dao.IRecordIncomeInfoDao;
import com.mrjy.maintain.dao.ISMSSendInfoDao;
import com.mrjy.maintain.dao.IServiceStationInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoDao;
import com.mrjy.maintain.dao.IUserBalanceInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.dao.IWechatSMSInfoDao;
import com.mrjy.maintain.dto.PromoteDetailDTO;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.maintain.util.SharingProportionEnum;
import com.mrjy.payment.dao.IOrderStatusInfoDao;
import com.mrjy.payment.dao.ITransferInfoDao;
import com.mrjy.payment.dao.IUserBalancePaymentDao;
import com.mrjy.payment.dao.IVipPackageInfoDao;
import com.mrjy.payment.dto.SpecialPaymentDTO;
import com.mrjy.payment.dto.UserBalancePaymentDto;
import com.mrjy.payment.dto.UserBalancePaymentSchoolDTO;
import com.mrjy.payment.dto.UserBalancePaymentSchoolTotalDTO;
import com.mrjy.queries.dao.IQuestionCommentDao;
import com.mrjy.queries.dao.IQuestionInfoDao;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IDistributorTeamInfoDao;
import com.mrjy.share.dao.IOperationCenterInfoDao;
import com.mrjy.share.dao.IPromotorLinkDao;
import com.mrjy.share.dao.IShareMemberDao;
import com.mrjy.share.dto.DistributorInfoDTO;
import com.mrjy.share.dto.PromoterDTO;
import com.mrjy.share.dto.PromotorLinkDTO;
import com.mrjy.video.dao.IVideoInfoDao;
import com.mrjy.video.dao.IVideoVipDao;
import com.mrjy.wechat.conts.WxConsts;
import com.mrjy.wechat.dto.TemplateMessage;
import com.mrjy.wechat.util.WeChatUtil;
import com.tencent.common.Configure;
import com.tencent.common.RandomStringGenerator;
import com.tencent.common.Signature;
import com.tencent.protocol.pay_protocol.ScanPayReqData;
import com.tencent.protocol.pay_protocol.ScanPayResData;

@Service("userBalancePaymentBo")
public class UserBalancePaymentBo implements IUserBalancePaymentBo{

	@Resource
	private IUserBalancePaymentDao userBalancePaymentDao;
	@Resource
	private IUserBalanceInfoDao userBalanceInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Resource
	private IMessageInfoDao messageInfoDao;
	@Resource
	private IOrderStatusInfoDao orderStatusInfoDao;
	@Resource
	private ISMSSendInfoDao smsSendInfoDao;
	@Resource
	private IUserMemberInfoDao userMemberInfoDao;
	@Resource
	private IShareMemberDao shareMemberDao;//分销--推荐成员信息表
	@Resource
	private ICoursePackageInfoDao coursePackageInfoDao;
	@Resource
	private ICoursePackageVipDao coursePackageVipDao;
	@Resource
	private IPromoteDetailDao promoteDetailDao;
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	@Resource
	private ITransferPaymentBo transferPaymentBo;//企业付款到零钱
	@Resource
	private ITransferInfoDao transferInfoDao;
	@Resource
	private IPartnerInfoDao partnerInfoDao;
	@Resource
	private IDistributorTeamInfoDao distributorTeamInfoDao;
	@Resource
	private IServiceStationInfoDao serviceStationInfoDao;
    @Resource
    private IQuestionInfoDao questionInfoDao;
    @Resource
    private IQuestionCommentDao questionCommentDao;
    @Resource
    private IRecordIncomeInfoDao recordIncomeInfoDao;
    @Resource
    private ITeacherInfoDao teacherInfoDao;
    @Resource
	private ISMSSendInfoBo smsSendInfoBo;
    @Resource
	private IVipPackageInfoDao vipPackageInfoDao;
    @Resource
    private IWechatSMSInfoDao wechatSMSInfoDao ;
    @Resource
    private IVideoInfoDao videoInfoDao;
    @Resource
    private IVideoVipDao videoVipDao;
    @Resource
    private RedisPool redisPool;
    @Resource
    private IIntegralExchangeDao integralExchangeDao;
    @Resource
    private IIntegralExchangedLogDao integralExchangedLogDao;
    @Resource
    private IHappinessInfoDao happinessInfoDao;
    @Resource
    private IActivityInfoDao activityInfoDao;
    @Resource
    private IActivitySignupInfoDao activitySignupInfoDao;
    @Resource
    private IPromotorLinkDao promotorLinkDao ;
    @Resource
    private IOperationCenterInfoDao operationCenterInfoDao ;

	private static  Log log=LogFactory.getLog(UserBalancePaymentBo.class);
	private static Logger logger = Logger.getLogger(UserBalancePaymentBo.class);


    @Override
    public Object beginPayment(UserBalancePayment userBalancePayment,UserInfo userInfo) {
		
//		String reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
//		userBalancePayment.setMoney(100.15f);
		userBalancePayment.setPrice(userBalancePayment.getMoney());
		if (userInfo != null) {
			StringBuffer sbHtml = new StringBuffer();
			sbHtml.append("<form id=\"orderForm\" action=\"payment/userBalance/submitPayment.do\" method=\"POST\">");	
			sbHtml.append("<input type=\"hidden\" name=\"userId\" value=\"" + userInfo.getId() + "\"/>");
			sbHtml.append("<input type=\"hidden\" name=\"typeId\" value=\"" + userBalancePayment.getTypeId() + "\"/>");
			sbHtml.append("<input type=\"hidden\" name=\"name\" value=\"" + userBalancePayment.getName() + "\"/>");
			sbHtml.append("<input type=\"hidden\" name=\"money\" value=\"" + userBalancePayment.getMoney() + "\"/>");
			sbHtml.append("</form>");
			userBalancePayment.setHtml(sbHtml.toString());
			userBalancePayment.setMessageString("success");
			return userBalancePayment;
		}else {
			return "userInfo_error";
		}
	}

	@Override
	public Object txSubmitPayment(UserBalancePayment userBalancePayment,UserInfo userInfo) {
		Map<String,Object> map = new HashMap<String, Object>();
		if (userInfo == null) {
			map.put("err_code", -1);
			map.put("err_msg", "当前用户未登录");
			return map;
		}
		if(null == userBalancePayment){
			map.put("err_code", -2);
			map.put("err_msg", "订单信息为空");
			return map;
		}else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date now = userBalancePaymentDao.getTime();
			if (userBalancePayment.getTypeId() == null) {
				map.put("err_code", -3);
				map.put("err_msg", "支付类型typeid为空");
				return map;
			}
			if (userBalancePayment.getMoney()==null) {
				map.put("err_code", -4);
				map.put("err_msg", "付款金额为空");
				return map;
			}
			String paymentCode = null ;
			//默认非特价
			userBalancePayment.setIsSpecial("0");
			Integer integralRequire = 0;
			if (userBalancePayment.getTypeId() ==1) {//余额充值
				paymentCode = "vim_" + userInfo.getId() + sdf.format(now);
				userBalancePayment.setName("余额充值");
			}else if (userBalancePayment.getTypeId() == 2) {//会员开通
				paymentCode = "vip_" + userInfo.getId() + sdf.format(now);
				//判断所选套餐与金额是否符合，符合插入订单，否则返回错误信息
				//通过传进来的会员套餐id查询套餐信息
                if (userBalancePayment.getVipPackageTypeId() == 0) {
                    map.put("err_code", 201);
					map.put("err_msg", "请选择套餐");
					return map;
				}
                VipPackageInfo vpi = vipPackageInfoDao.queryById(userBalancePayment.getVipPackageTypeId());
                if(vpi == null){
					map.put("err_code", 202);
					map.put("err_msg", "根据会员套餐类型id查询不到套餐，请联系系统管理员");
					return map;
				}
				if(vpi.getDiscountPrice() == null){
					map.put("err_code", 203);
					map.put("err_msg", "会员套餐的价格不存在，请联系系统管理员");
					return map;
				}
				if(vpi.getDiscountPrice().setScale(2, BigDecimal.ROUND_HALF_UP )
						.compareTo(new BigDecimal(userBalancePayment.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP )) != 0){
					map.put("err_code", 204);
					map.put("err_msg", "选择套餐的付款金额不正确");
					return map;
				}
			}else if(userBalancePayment.getTypeId() == 4){//课程包
				paymentCode = "cpk_" + userInfo.getId() + sdf.format(now);
				CoursePackageInfoDTO vo = new CoursePackageInfoDTO();
				vo.setId(userBalancePayment.getPaymentProgramId());
				CoursePackageInfo courseInfo = coursePackageInfoDao.selectById(vo);
				if(courseInfo == null){
					map.put("err_code", 301);
					map.put("err_msg", "无法找到课程包相关信息");
					return map;
				}else{
					if(Math.abs(userBalancePayment.getMoney().floatValue() - courseInfo.getDiscountPrice().floatValue()) > 0){
						map.put("err_code", 302);
						map.put("err_msg", "支付的金钱和课程包的定价不相等");
						return map;
					}
					//是否特价
					userBalancePayment.setIsSpecial(courseInfo.getIsSpecial());
				}
			}else if(userBalancePayment.getTypeId() == 5){//分销商升级
				paymentCode = "dtb_" + userInfo.getId() + sdf.format(now);
				DistributorInfoDTO diDTO = distributorInfoDao.queryByIdNoDisableFlag(userBalancePayment.getPaymentProgramId());
				if(diDTO == null){
					map.put("err_code", 401);
					map.put("err_msg", "无法找到分销商相关信息");
					return map;
				}else{
					if(diDTO.getFuCardNum() == 20 ){//福卡数为20张
						if(Math.abs(userBalancePayment.getMoney().floatValue() - 4000.0f) > 0){
							map.put("err_code", 402);
							map.put("err_msg", "选择福卡套餐的付款金额不正确");
							return map;
						}
					}else if(diDTO.getFuCardNum() == 50){//福卡数为50张
						if(Math.abs(userBalancePayment.getMoney().floatValue() - 10000.0f) > 0){
							map.put("err_code", 403);
							map.put("err_msg", "选择福卡套餐的付款金额不正确");
							return map;
						}
					}else{
						map.put("err_code", 404);
						map.put("err_msg", "购买的福卡数不对");
						return map;
					}
				}

            } else if (userBalancePayment.getTypeId() == 6) {//语音偷听
                paymentCode = "monitor_" + userInfo.getId() + sdf.format(now);
                if (StringUtils.isBlank(userBalancePayment.getMessageString())) {
                    map.put("err_code", 501);
                    map.put("err_msg", "用户id为空");
                    return map;
                }
                if (Math.abs(userBalancePayment.getMoney().floatValue() - 1.0f) > 0) {
                    map.put("err_code", 502);
                    map.put("err_msg", "付款金额不正确");
                    return map;
                }
            }else if( userBalancePayment.getTypeId() == 7){//学校推广的会员付款
            	paymentCode = "vip_" + userInfo.getId() + sdf.format(now);
            	//通过传进来的会员套餐id查询套餐信息
                if (userBalancePayment.getVipPackageTypeId() == 0) {
                    map.put("err_code", 701);
					map.put("err_msg", "请选择套餐");
					return map;
				}
                VipPackageInfo vpi = vipPackageInfoDao.queryById(userBalancePayment.getVipPackageTypeId());
                if(vpi == null){
					map.put("err_code", 702);
					map.put("err_msg", "根据会员套餐类型id查询不到套餐，请联系系统管理员");
					return map;
				}
				if(vpi.getDiscountPrice() == null){
					map.put("err_code", 703);
					map.put("err_msg", "会员套餐的价格不存在，请联系系统管理员");
					return map;
				}
				if(vpi.getDiscountPrice().setScale(2, BigDecimal.ROUND_HALF_UP )
						.compareTo(new BigDecimal(userBalancePayment.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP )) != 0){
					map.put("err_code", 704);
					map.put("err_msg", "选择套餐的付款金额不正确");
					return map;
				}
            } else if (userBalancePayment.getTypeId() == 8) {//语音提问
                paymentCode = "record_" + userInfo.getId() + sdf.format(now);
                int teacher_id;
                if (StringUtils.isBlank(userBalancePayment.getMessageString())) {
                    map.put("err_code", 501);
                    map.put("err_msg", "明师id为空");
                    return map;
                } else {
                    teacher_id = Integer.parseInt(userBalancePayment.getMessageString());
                }
                TeacherInfo vo = new TeacherInfo();
				vo.setUserId(teacher_id);
				vo.setDisableFlag(0);
                TeacherInfo teacherInfo = teacherInfoDao.queryByUserId(vo);

                BigDecimal askedPrice = teacherInfo.getAskedPrice();
                BigDecimal balance = new BigDecimal(userBalancePayment.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (askedPrice.compareTo(balance) != 0) {
                    map.put("err_code", 502);
                    map.put("err_msg", "金额不匹配");
                    return map;
                }
            }else if (userBalancePayment.getTypeId() == 9) { //微课
            	paymentCode = "vid_" + userInfo.getId() + sdf.format(now);
				VideoInfo videoInfo = (VideoInfo) videoInfoDao.queryById(userBalancePayment.getPaymentProgramId());
				if(videoInfo == null){
					map.put("err_code", 901);
					map.put("err_msg", "无法找到微课相关信息");
					return map;
				}else{
					if(Math.abs(userBalancePayment.getMoney().floatValue() - videoInfo.getOriginalPrice().floatValue()) > 0){
						map.put("err_code", 902);
						map.put("err_msg", "支付的金钱和微课的定价不相等");
						return map;
					}
					//是否特价
					//userBalancePayment.setIsSpecial(videoInfo.getIsSpecial());
				}
			}else if (userBalancePayment.getTypeId() == 10) { //活动
				Integer amount = (userBalancePayment.getAmount()==null?1:userBalancePayment.getAmount());
				paymentCode = "act_" + userInfo.getId() + sdf.format(now);
				ActivityInfo activityInfo =  activityInfoDao.selectById(userBalancePayment.getPaymentProgramId());
				if(activityInfo == null){
					map.put("err_code", 1001);
					map.put("err_msg", "无法找到活动相关信息");
					return map;
				}else{
					//判断用户身份, vip和普通用户需要支付的金额不一样
					UserMemberInfo vip = userMemberInfoDao.selectIsVipByUserId(userInfo.getId());
					int integralBalance = userInfoDao.queryIntegralBalanceByUserId(userInfo.getId());
					BigDecimal moneyRequire = null;
					if (null==vip) {//非会员
						moneyRequire = activityInfo.getOriginalMoneyRequire().multiply(new BigDecimal(amount));
						integralRequire = activityInfo.getOriginalIntegralRequire() * amount;
					}else {
						moneyRequire = activityInfo.getVipMoneyRequire().multiply(new BigDecimal(amount));
						integralRequire = activityInfo.getVipIntegralRequire() * amount;
					}
					if (integralBalance < integralRequire.intValue()) {
						map.put("err_code", 1002);
						map.put("err_msg", "积分不足,无法报名");
						return map;
					}
					if(new BigDecimal(Float.toString(userBalancePayment.getMoney())).compareTo(moneyRequire) != 0){
						map.put("err_code", 1003);
						map.put("err_msg", "支付金额有误");
						return map;
					}
				}
				if(userBalancePayment.getAmount() == null){
					userBalancePayment.setAmount(amount);
				}
				//是活动
				userBalancePayment.setIsSpecial("2");
			} else {
                map.put("err_code", 1);
				map.put("err_msg", "付款类型不对");
				return map;
			}
			/*
			 * 使用了代金券(购买特价课程包,报名活动 不能使用代金券）
			 */
			if (userBalancePayment.getVoucherId() != null && !"1".equals(userBalancePayment.getIsSpecial())
					&& !ConstantsUtil.getProperty("PAYMENT_TYPE.ACTIVITY").equals(String.valueOf(userBalancePayment.getTypeId()))) {
				//判断用户是否可用这张代金券
				IntegralExchangedLog log = integralExchangedLogDao.isAvailable(userBalancePayment.getVoucherId());
				if (log==null) {
					map.put("err_code", -5);
					map.put("err_msg", "该代金券不可用(已过期或已使用)");
					return map;
				}
				IntegralExchange exchange = integralExchangeDao.queryById(log.getIntegralExchangeId());
				if (exchange==null) {
					map.put("err_code", -6);
					map.put("err_msg", "该代金券不存在");
					return map;
				}
                if (exchange.getTypeId() == 2 && userBalancePayment.getMoney() != 365f) {
                    map.put("err_code", -7);
                    map.put("err_msg", "政府补助券仅能在开通全年会员时使用");
                    return map;
                }

                BigDecimal discountMoney = new BigDecimal(userBalancePayment.getMoney()).subtract(new BigDecimal(exchange.getVoucherMoney()));
                //保留两位小数
                DecimalFormat df = new DecimalFormat("#.00");
                Float f = Float.valueOf(df.format(discountMoney.doubleValue()));
                //下单金额=传入的原价-代金券金额 (若小于0, 则置为0)
                if (discountMoney.compareTo(new BigDecimal(0)) == -1) {
                    f = new BigDecimal(0).floatValue();
                }
				userBalancePayment.setMoney(f);
			}
			userBalancePayment.setUserId(userInfo.getId());	
			UserBalancePayment existUnpaidPayment = userBalancePaymentDao.queryUnpaidByUserId(userBalancePayment); 
			//如果实付金额等于0,则直接处理业务逻辑返回,不调用微信/支付宝支付接口
			if (new BigDecimal(userBalancePayment.getMoney()).compareTo(new BigDecimal(0)) == 0) {
				int row = 0;
				if (existUnpaidPayment == null) {
					userBalancePayment.setCode(paymentCode);
					userBalancePayment.setIntegral(integralRequire);
					userBalancePayment.setCompleteTime(now);
					userBalancePayment.setOrderTime(now);
					userBalancePayment.setStatusId(2);
					userBalancePayment.setPaymentMethod("wxqrpay");
					row = userBalancePaymentDao.insert(userBalancePayment);
				}else{
					existUnpaidPayment.setCode(paymentCode);
					existUnpaidPayment.setIntegral(integralRequire);
					existUnpaidPayment.setOrderTime(now);
					existUnpaidPayment.setCompleteTime(now);
					existUnpaidPayment.setMoney(userBalancePayment.getMoney());	
					existUnpaidPayment.setName(userBalancePayment.getName());
					existUnpaidPayment.setStatusId(2);
					existUnpaidPayment.setPaymentMethod("wxqrpay");
					existUnpaidPayment.setAmount(userBalancePayment.getAmount());
					existUnpaidPayment.setVoucherId(userBalancePayment.getVoucherId());
					if( userBalancePayment.getTypeId() == 2 || userBalancePayment.getTypeId() == 7){
						existUnpaidPayment.setVipPackageTypeId(userBalancePayment.getVipPackageTypeId());
					}
					row = userBalancePaymentDao.updatePayment(existUnpaidPayment);
				}
				if (row != 1) {
					map.put("err_code", 3);
					map.put("err_msg", "购买失败");
				}else{
					if (existUnpaidPayment==null) {
						txUpdateUserBalance(userBalancePayment, userBalancePayment.getMoney());
					}else {
						txUpdateUserBalance(existUnpaidPayment, userBalancePayment.getMoney());
					}
					if(userBalancePayment.getTypeId() == 10){
						map.put("activityPayId", userBalancePayment.getId());
					}
					map.put("err_code", 200);
					map.put("err_msg", "购买成功");
					
				}
				return map;
			}
			System.out.println("----------------------------------------->paymentCode:" + paymentCode);
			if (existUnpaidPayment == null) {
				userBalancePayment.setIntegral(integralRequire);
				userBalancePayment.setCode(paymentCode);
				userBalancePayment.setOrderTime(now);
				userBalancePayment.setStatusId(1);
				int row = userBalancePaymentDao.insert(userBalancePayment);
				if (row != 1) {
					map.put("err_code", 2);
					map.put("err_msg", "插入不成功");
				}else {
					userBalancePayment.setUrl("/payment/userBalance/getPaymentByCode.do?code▲" + userBalancePayment.getCode());
					if(userBalancePayment.getTypeId() == 10){
						map.put("activityPayId", userBalancePayment.getId());
					}
					map.put("err_code", 0);
					map.put("err_msg", "插入成功");
					map.put("userBalancePayment", userBalancePayment);
				}
			}else{
				System.out.println("----------------------------------------->paymentCode:" + paymentCode);
				System.out.println("----------------------------------------->start：existUnpaidPayment.getCode()--" + existUnpaidPayment.getCode());
				existUnpaidPayment.setCode(paymentCode);
				existUnpaidPayment.setIntegral(integralRequire);
				existUnpaidPayment.setOrderTime(now);
				existUnpaidPayment.setMoney(userBalancePayment.getMoney());	
				existUnpaidPayment.setName(userBalancePayment.getName());
				//新增小程序付款形式
				if(StringUtils.isNotBlank(userBalancePayment.getPaymentMethod())){
					existUnpaidPayment.setPaymentMethod(userBalancePayment.getPaymentMethod());
				}
				if( userBalancePayment.getTypeId() == 2 || userBalancePayment.getTypeId() == 7){
					existUnpaidPayment.setVipPackageTypeId(userBalancePayment.getVipPackageTypeId());
				}
				
				int row = userBalancePaymentDao.updatePayment(existUnpaidPayment);
				if (row != 1) {
					map.put("err_code", 3);
					map.put("err_msg", "更新不成功");
				}else{
					if(userBalancePayment.getTypeId() == 10){
						map.put("activityPayId", userBalancePayment.getId());
					}
					userBalancePayment.setUrl("/payment/userBalance/getPaymentByCode.do?code▲" + existUnpaidPayment.getCode());
					System.out.println("----------------------------------------->end：existUnpaidPayment.getCode()--" + existUnpaidPayment.getCode());
					map.put("err_code", 0);
					map.put("err_msg", "更新成功");
					map.put("userBalancePayment", userBalancePayment);
				}
			}
		}
		return map;
	}

	@Override
	public Object getPaymentByCode(String code) {
		UserBalancePayment userBalancePaymentCheck = userBalancePaymentDao.selectByCode(code); 
		if (userBalancePaymentCheck == null) {
			userBalancePaymentCheck = new UserBalancePayment();
			userBalancePaymentCheck.setCode(code);
			userBalancePaymentCheck.setMessageString("fail");
			userBalancePaymentCheck.setUrl("/payment/userBalance/validatePay.do?code=" + userBalancePaymentCheck.getCode());
		}else {
			userBalancePaymentCheck.setMessageString("success");
			userBalancePaymentCheck.setUrl("/payment/userBalance/validatePay.do?code=" + userBalancePaymentCheck.getCode());
		}
		return userBalancePaymentCheck;
	}

	@Override
	public Object validatePay(String code) {
		UserBalancePayment userBalancePaymentCheck = userBalancePaymentDao.selectByCode(code);
		if (userBalancePaymentCheck == null) {
			userBalancePaymentCheck = new  UserBalancePayment();
			userBalancePaymentCheck.setCode(code);
			userBalancePaymentCheck.setMessageString("fail");
			return userBalancePaymentCheck;
		}else {
			if (userBalancePaymentCheck.getStatusId().intValue()==2) {
				if (userBalancePaymentCheck.getTypeId().intValue()==1) {
					userBalancePaymentCheck.setHtml("你的余额充值已经成功付款，请查看。<a id='submitorder' class='btn btn-success' href='../home/vip/vip_center.html'>支付完成</a>");	
				}else {
					userBalancePaymentCheck.setHtml("你的会员充值已经成功付款，请查看。<a id='submitorder' class='btn btn-success' href='../home/vip/vip_center.html'>支付完成</a>");
				}
				userBalancePaymentCheck.setMessageString("success");
				return userBalancePaymentCheck;
			} else {
				userBalancePaymentCheck.setMessageString("fail");
				userBalancePaymentCheck.setReturn_url("payment/userBalance/returnUrl.do");
				userBalancePaymentCheck.setNotify_url("payment/userBalance/notifyUrl.do");
				userBalancePaymentCheck.setWxnotify_url("/payment/userBalance/WXnotifyUrl.do");
				userBalancePaymentCheck.setClassName("userBalancePaymentBo");
				return userBalancePaymentCheck;
			}
		}
	}

	@Override
	public UserBalancePayment txReturnUrl(Map<String, String> params,
			String out_trade_no, String trade_no, String trade_status,
			Float money) {
		//本地检查是否已支付成功
		UserBalancePayment userBalancePayment = userBalancePaymentDao.selectCompleteByCode(out_trade_no);
		if (userBalancePayment != null) {
			userBalancePayment.setUrl("payment/userBalance/validatePay.do?code▲" + out_trade_no);
			userBalancePayment.setMessageString("payment/payment_success");
			return userBalancePayment;
		}
		// 计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);
		
		UserBalancePayment userBalancePaymentExist = userBalancePaymentDao.selectByCode(out_trade_no);
		
		if (verify_result) {// 验证成功
			if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
				if (userBalancePaymentExist == null) {
					userBalancePaymentExist = new UserBalancePayment();
					userBalancePaymentExist.setUrl("payment/userBalance/validatePay.do?code▲" + out_trade_no);
					userBalancePaymentExist.setMessageString("payment/payment_fail");
					return userBalancePaymentExist;
				}
				userBalancePaymentExist.setUrl("payment/userBalance/validatePay.do?code▲" + out_trade_no);
				if (userBalancePaymentExist.getMoney().floatValue() != money.floatValue()) {
					userBalancePaymentExist.setMessageString("payment/payment_fail");
					return userBalancePaymentExist;
				}
				userBalancePaymentExist.setCompleteTime(userBalancePaymentDao.getTime());
				userBalancePaymentExist.setStatusId(2);
				userBalancePaymentExist.setPaymentMethod("alipay");
				userBalancePaymentExist.setTradeNo(trade_no);
				int rows = userBalancePaymentDao.updatePayment(userBalancePaymentExist);
				if (rows != 1) {
					userBalancePaymentExist.setMessageString("payment/payment_fail");
					return userBalancePaymentExist;
				}
				userBalancePaymentExist.setMessageString("payment/payment_success");
				//用户余额更新
				txUpdateUserBalance(userBalancePaymentExist, money);
				//txSendMsg(userBalancePaymentExist);
			}else {
				userBalancePaymentExist.setMessageString("payment/payment_fail");
			}
			return userBalancePaymentExist;
		}else {
			if (userBalancePaymentExist == null) {
				userBalancePaymentExist = new UserBalancePayment();
			}
			userBalancePaymentExist.setUrl("payment/userBalance/validatePay.do?code▲" + out_trade_no);
			userBalancePaymentExist.setMessageString("payment/payment_fail");
			return userBalancePaymentExist;
		}
	}
	
	@Override
	public String notifyUrl(Map<String, String> params, String out_trade_no,
			String trade_no, String trade_status, Float money) {
		// 先本地检查，看是否已经支付成功
		UserBalancePayment  userBalancePayment = userBalancePaymentDao.selectCompleteByCode(out_trade_no);
		if (userBalancePayment != null) {
			return "success";
		}
		if (AlipayNotify.verify(params)) {// 验证成功
			if (trade_status.equals("TRADE_FINISHED")|| trade_status.equals("TRADE_SUCCESS")) {
				UserBalancePayment userBalancePaymentExist = userBalancePaymentDao.selectWaitingByCode(out_trade_no);
				if (userBalancePaymentExist == null|| userBalancePaymentExist.getMoney().floatValue() != money.floatValue()) {
					return "fail";
				}
				userBalancePaymentExist.setCompleteTime(userBalancePaymentDao.getTime());
				userBalancePaymentExist.setStatusId(2);
				userBalancePaymentExist.setPaymentMethod("alipay");
				userBalancePaymentExist.setTradeNo(trade_no);
				int rows = userBalancePaymentDao.updatePayment(userBalancePaymentExist);
				
				if (rows != 1) {
					return "fail";
				} else {
					//用户余额更新
					txUpdateUserBalance(userBalancePaymentExist ,money);
					//txSendMsg(userBalancePaymentExist);
					return "success";
				}
			} else {
				return "fail";
			}
	    }else {
	    	return "fail";
		}
	}
	
	
	@Override
	public String WXnotifyUrl(ScanPayResData scanPayResData) {
				// 先本地检查，看是否已经支付成功
				UserBalancePayment userBalancePaymentCheck = userBalancePaymentDao.selectCompleteByCode(scanPayResData.getOut_trade_no());
				if (userBalancePaymentCheck != null) {
					//支付成功
					return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
					        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				}
				if("SUCCESS".equals(scanPayResData.getResult_code())){
					UserBalancePayment userBalancePaymentExist = userBalancePaymentDao.selectWaitingByCode(scanPayResData.getOut_trade_no());
					if (userBalancePaymentExist == null) {
						return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[订单不存在]]></return_msg>" + "</xml> ";
					}
					int total_fee = (int) Math.round(userBalancePaymentExist.getMoney()*100);
					if(total_fee != scanPayResData.getTotal_fee()){
						return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[金额不相等]]></return_msg>" + "</xml> ";
					}
					
					userBalancePaymentExist.setCompleteTime(userBalancePaymentDao.getTime());
					userBalancePaymentExist.setStatusId(2);
					userBalancePaymentExist.setPaymentMethod("wxqrpay");
					userBalancePaymentExist.setTradeNo(scanPayResData.getOut_trade_no());
					int rows = userBalancePaymentDao.updatePayment(userBalancePaymentExist);
					if (rows != 1) {
						return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[更新订单数据失败]]></return_msg>" + "</xml> ";
					} else {
						//type==1:user_balance_nfo更新;type==2:user_Banlance_payment,share_member_info，user_member_info更新，给推荐人发短信;
						boolean flag = txUpdateUserBalance(userBalancePaymentExist,(scanPayResData.getTotal_fee()+0.0f)/100);
						//txSendMsg(userBalancePaymentExist);
						if(flag){			
							//支付成功
							return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
									+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
						}else{							
							return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[更新订单数据失败]]></return_msg>" + "</xml> ";
						}
					}
				}else {
					return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[支付失败]]></return_msg>" + "</xml> ";
				}
	}

    @Override
    public Object WXPollingNotify(ScanPayResData scanPayResData) {
        // 先本地检查，看是否已经支付成功
        return WXnotifyUrl(scanPayResData);
	}

	@Override
	public Object queryUserBalancePayments(UserInfo userInfo) {
		if (userInfo != null) {
			UserBalancePayment ubp = new UserBalancePayment();
			ubp.setUserId(userInfo.getId());
			ubp.setTypeId(1);//查询30天充值记录
			List<UserBalancePayment> uPayments = userBalancePaymentDao.queryPaymentByUserId(ubp);
			if (uPayments.size()==0) {
				return "noData";
			}
			for (UserBalancePayment userBalancePayment : uPayments) {
				String orderTimeString = DateUtil.dateToString(userBalancePayment.getOrderTime(), DateUtil.FULL_DATE);
				userBalancePayment.setOrderTimeString(orderTimeString);
				if (userBalancePayment.getCompleteTime() != null) {
					String completeTimeString = DateUtil.dateToString(userBalancePayment.getCompleteTime(), DateUtil.FULL_DATE);
					userBalancePayment.setCompleteTimeString(completeTimeString);
				}
			}
			return uPayments;
		}
		return "userInfo_error";
	}

	@Override
	public Object updatePaymentFlag(UserInfo userInfo,UserBalancePayment userBalancePayment) {
		if (userInfo == null) {
			return "userInfo_error";
		}
		UserBalancePayment u = userBalancePaymentDao.queryById(userBalancePayment.getIds()[0]);
		if (u != null) {
			if (u.getUserId() == userInfo.getId() || u.getUserId().intValue() == userInfo.getId().intValue()) {
				int row = userBalancePaymentDao.updateDeleteFlag(userBalancePayment.getIds());
				return row;
			}
		}
		
		return "data_error";
	}

	@Override
	public Object deleteByIds(UserInfo userInfo, int[] ids) {
		if (userInfo == null) {
			return "userInfo_error";
		}
		UserBalancePayment userBalancePayment = userBalancePaymentDao.queryById(ids[0]);
		if (userBalancePayment != null && userBalancePayment.getStatusId().intValue()==1) {
			if (userBalancePayment.getUserId() == userInfo.getId() || userBalancePayment.getUserId().intValue() == userInfo.getId().intValue()) {
				return userBalancePaymentDao.deletePaymentByIds(ids);
			}
		}
		return "data_error";
	}

	@Override
	public  Object txBalancePay(UserBalanceInfo userBalanceInfo, UserInfo userInfo) {
		if (userInfo == null) {
			return "userInfo_error";
		}
		UserBalancePayment userBalancePayment = userBalancePaymentDao.selectByCode(userBalanceInfo.getOrderCode());
		if (userBalancePayment!= null && userBalancePayment.getTypeId().intValue() == 2 && userBalancePayment.getStatusId().intValue()==1 ) {
			UserBalanceInfo ubi = userBalanceInfoDao.queryByUserId(userInfo.getId());
			if (ubi != null && ubi.getMoney().floatValue()>=userBalancePayment.getMoney().floatValue()) {
				if (MD5Encrypt.validatePassword(userBalanceInfo.getPayPasswordString(), ubi.getPayPassword())) {
					//余额支付
					ubi.setMoney(ubi.getMoney()-userBalancePayment.getMoney());
					
	
					int row = userBalanceInfoDao.updateById(ubi);
					if (row != 1) {
						return "pay_error";
					}
					userBalancePayment.setCompleteTime(new Date());
					userBalancePayment.setStatusId(2);
					userBalancePayment.setPaymentMethod("balance");
					int r = userBalancePaymentDao.updatePayment(userBalancePayment);
					if (r != 1) {
						return "pay_error";
					}
					DecimalFormat decimalFormat = new DecimalFormat(".00");
					MessageInfo messageInfo = new MessageInfo();
					messageInfo.setTitle("余额支付信息");
					messageInfo.setContent("你的余额支出"+decimalFormat.format(userBalancePayment.getMoney())+"元。当前余额还有"+decimalFormat.format(ubi.getMoney())+"元。");
					messageInfo.setSendTime(new Date());
					messageInfo.setSenderId(1);
					messageInfo.setUserId(ubi.getUserId());
					messageInfo.setReadTag(0);
					messageInfo.setMsgModule(1);
					messageInfoDao.insert(messageInfo);
					
					return "ok";
				}else {
					return "pw_error";
				}
			}else {
				return "money_error";
			}
		}else {
			return "code_error";
		}
	}

	@Override
	public OrderInfo selectWaitingByCode(String code) {
		UserBalancePayment userBalancePayment = userBalancePaymentDao.selectWaitingByCode(code);
		if (userBalancePayment == null) {
			userBalancePayment = new UserBalancePayment();
			userBalancePayment.setCode(code);
			userBalancePayment.setMessageString("fail");
		}
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setName(userBalancePayment.getName());
		orderInfo.setMoney(userBalancePayment.getMoney());
		orderInfo.setUserId(userBalancePayment.getUserId());
		return orderInfo;
	}

	@Override
	public OrderInfo doScanPayBusiness(String Code) {
		UserBalancePayment userBalancePayment = userBalancePaymentDao.selectByCode(Code);
		if (userBalancePayment == null) {
			userBalancePayment = new UserBalancePayment();
			userBalancePayment.setCode(Code);
			userBalancePayment.setMessageString("fail");
		}else if(userBalancePayment.getStatusId() != 1){
			userBalancePayment.setMessageString("fail");
		}
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setName(userBalancePayment.getName());
		orderInfo.setMoney(userBalancePayment.getMoney());
		orderInfo.setCode(userBalancePayment.getCode());
		orderInfo.setMessageString(userBalancePayment.getMessageString());
		return orderInfo;
	}
	
	//更新用户余额信息  
	private boolean txUpdateUserBalance(UserBalancePayment userBalancePayment,Float money){
		Integer userId = userBalancePayment.getUserId();
		Integer typeId = userBalancePayment.getTypeId();
        Timestamp startTime = null;//（会员，课程包，微课）开始时间  插入通知时用
        Timestamp endTime = null;//（会员，课程包，微课）到期时间  插入通知时用

        int row = 0;
        if (typeId == 1) {//余额充值
            UserBalanceInfo userBalanceInfo = userBalanceInfoDao.queryByUserId(userId);
            if (userBalanceInfo == null) {
                userBalanceInfo = new UserBalanceInfo();
                userBalanceInfo.setMoney(money);
                userBalanceInfo.setUserId(userId);
                UserInfo user=userInfoDao.queryById(userId);
				String mobilePhone = user.getMobilePhone();
				String defaultPassword = mobilePhone.substring(5);//默认支付密码为手机号码后6位
				userBalanceInfo.setPayPassword(MD5Encrypt.encryptByMD5(defaultPassword));
				row = userBalanceInfoDao.insert(userBalanceInfo);
			}else {
				userBalanceInfo.setMoney(userBalanceInfo.getMoney() + money);
				row = userBalanceInfoDao.updateById(userBalanceInfo);
			}
		}else if(typeId==2 || typeId == 7){//开通套餐,学校推广会员
			UserInfo user = userInfoDao.queryById(userId);
			if(user.getId() > 0){
				//新增需求 获得积分
				IntegralInfo intetral = IntegralUtil.setIntegral(user.getId()
						, (int)(IntegralEnum.BUY_VIP.getScore()*money)
						, IntegralEnum.BUY_VIP.getTypeDesc(), IntegralEnum.BUY_VIP.getTypeId()
						, userBalancePayment.getId()); 
				
				//更新 member_ship
				UserMemberInfo memberInfo = new UserMemberInfo();
				memberInfo.setUserId(user.getId());
				//通过套餐类型id查询套餐信息
                VipPackageInfo vpi = vipPackageInfoDao.queryById(userBalancePayment.getVipPackageTypeId());
                //开通会员的月数
				int add_vip_months = 0 ;
                int add_vip_days = 0;
                if(vpi != null ){
					if(vpi.getMonths() != null){
						add_vip_months = vpi.getMonths() ;
					}else {
						log.error("会员套餐对象vpi的月数：------->"+ vpi.getMonths() );
					}

                    if (vpi.getDays() != null) {
                        add_vip_days = vpi.getDays();
                    } else {
                        log.error("会员套餐对象vpi的天月数：------->" + vpi.getDays());
                    }
                    //针对36.5，一折活动，如果是特殊的话，则推广机制使用默认，即走之前特价课的通道
                    userBalancePayment.setIsSpecial(vpi.getIsSpecial());
                }else{
					log.error("会员套餐对象vpi：------->"+ vpi );
				}
				/*//开通会员的年份
				int add_vip_year = 0;
				if(Math.abs(money - 365.0f) <= 0){
					add_vip_year = 1;
				}else if(Math.abs(money - 520.0f) <= 0){
					add_vip_year = 2;
				}*/
				List<UserMemberInfo> list = userMemberInfoDao.selectListByUserId(memberInfo);
				if(null != list && list.size() > 0){ //之前是会员，有记录
					memberInfo = list.get(0);//查询是查处有效期最新的一条
					//如果有效期比当前时间大，则，使用有效期时间加相应的月份数，否则用当前时间加相应的月份数，并把开始时间改成当前时间
					if (memberInfo.getEndDate() - System.currentTimeMillis() > 0) {
                        startTime = new Timestamp(memberInfo.getEndDate());//msg
                        if (add_vip_months != 0) {
                            memberInfo.setEndDate(DateUtil.dateTimeAddMonths(memberInfo.getEndDate(), add_vip_months));//有效期 ，续费增加相应的月份数
                        }
                        if (add_vip_days != 0) {
                            memberInfo.setEndDate(DateUtil.dateTimeAddDays(memberInfo.getEndDate(), add_vip_days));//有效期 ，续费增加相应的天数
                        }
                        endTime = new Timestamp(memberInfo.getEndDate());

                    }else {
                        startTime = new Timestamp(System.currentTimeMillis());//msg
                        if (add_vip_months != 0) {
                            memberInfo.setEndDate(DateUtil.dateTimeAddMonths(System.currentTimeMillis(), add_vip_months));//有效期 ，续费相应的月份数
                        }
                        if (add_vip_days != 0) {
                            memberInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), add_vip_days));//有效期 ，续费相应的天数
                        }
                        endTime = new Timestamp(memberInfo.getEndDate());
                        memberInfo.setStartDate(System.currentTimeMillis());
					}
					memberInfo.setMembershipFlag(1);
					row = userMemberInfoDao.updateById(memberInfo);
				}else {
                    Long VipTime = System.currentTimeMillis();
                    startTime = new Timestamp(VipTime);
                    if (add_vip_months != 0) {
                        VipTime = DateUtil.dateTimeAddMonths(VipTime, add_vip_months);
                    }
                    if (add_vip_days != 0) {
                        VipTime = DateUtil.dateTimeAddDays(VipTime, add_vip_days);
                    }
                    endTime = new Timestamp(VipTime);
                    memberInfo.setUserId(user.getId());
					memberInfo.setMembershipFlag(1);
					memberInfo.setStartDate(new Date().getTime());
                    memberInfo.setEndDate(VipTime);//有效期 ，续费相应的月份数和天数
                    memberInfo.setGradeId(38);//默认小学一年级
					memberInfo.setDisableFlag(0);
					row = userMemberInfoDao.insert(memberInfo);
				}
				if(row == 1){
					//开通会员成功，新增一条我的消息
					MessageInfo messageInfo = new MessageInfo();
					messageInfo.setTitle("会员开通通知");
					messageInfo.setContent("恭喜！您已成功开通"+ add_vip_months +"个月的365家长课堂会员");
					messageInfo.setSendTime(new Date());
					messageInfo.setSenderId(1);
					messageInfo.setUserId(userId);
					messageInfo.setReadTag(0);
					messageInfo.setMsgModule(1);//会员开通成功通知
                    messageInfo.setStartTime(startTime);
                    messageInfo.setEndTime(endTime);
                    messageInfoDao.insert(messageInfo);
					
					//发送微信通知
					if(StringUtils.isNotBlank(user.getWeixinOpenid())){
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WeChatUtil.sendWechatTemplateMessageVip( user.getId().toString()
								, user.getUserName(), user.getMobilePhone(), sdf.format(memberInfo.getEndDate())
								, WxConsts.PUBLIC_DOMAIN + "/index.html?from=weClasses/weClasses.html", user.getWeixinOpenid());
						
					}
					
				}
			}
			Map<String , Object> map = null ;
			if(typeId == 2){
				map = insertPromoteDetail(userBalancePayment);
			}else if(typeId == 7){
				//如果是服务站升级学校实现独立端口的，则进入推广明细 
				//新增需求 20180828 
				Integer roleId = userBalancePaymentDao.selectRoleIdByPaymentId(userBalancePayment.getId());
				if(null != roleId && roleId == RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId().intValue()){
					map = insertPromoteDetail(userBalancePayment);
				}
			}
			if(map != null && (int)map.get("err_code") == 0){
				String[] userIds = ((String)map.get("recommendId")).split("@_@");
				String[] moneys = ((String)map.get("divideMoney")).split("@_@");
				UserInfo payer = userInfoDao.queryById(userBalancePayment.getUserId());
				Integer promoterId = (Integer) map.get("promoterId");
				UserInfo promoter = null;
				if (promoterId != null) {
					promoter = userInfoDao.queryById(promoterId);
				}
				for (int i = 0; i< userIds.length; i++) {
					UserInfo ui = userInfoDao.queryById(Integer.parseInt(userIds[i]));
					if(ui !=null ){
						String first = "您有一笔365家长课堂推广收入，请笑纳";
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						
						//判断当前时间是否在06:00-23:00，如果不是，把消息体保存到数据表，等6点统一发送；否则及时发
						if(DateUtil.betweenTime()){
							if(StringUtils.isNotBlank(ui.getWeixinOpenid())){
								WeChatUtil.sendWechatTemplateMessageIncome(first ,moneys[i]
										, userBalancePayment.getTradeNo() ,sdf.format(userBalancePayment.getCompleteTime())
										, WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html"
										, ui.getWeixinOpenid());
							}
							
							if(StringUtils.isNotBlank(ui.getMobilePhone())){
								//给推广人发短信通知
								Map<String , Object> smsParamMap = new HashMap<String , Object>();
								smsParamMap.put("name", CharSetUtil.strToReplace(ui.getUserName(), 6, "**"));
								smsParamMap.put("income", moneys[i]);
								if (promoter != null) {
									smsParamMap.put("pro", CharSetUtil.strToReplace(promoter.getUserName(), 6, "**"));
								}
								smsParamMap.put("payer", CharSetUtil.strToReplace(payer.getUserName(), 6, "**"));
								smsParamMap.put("time", DateUtil.dateToString(userBalancePayment.getCompleteTime(), DateUtil.FULL_DATE_NO_SECOND));
								if (i == 0 || promoter == null) {
									smsSendInfoBo.sendSMSAndAddRecord(ui.getMobilePhone(), smsParamMap
											, SMSTemplate.TEMPLATE_11, "2", "0");
								}else {
									smsSendInfoBo.sendSMSAndAddRecord(ui.getMobilePhone(), smsParamMap
											, SMSTemplate.TEMPLATE_12, "2", "0");
								}
							}
						}else{
							PromoteDetailDTO dto = new PromoteDetailDTO() ;
							dto.setRecommendId(ui.getId());
							PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
							
							WechatSMSInfo wSMSInfo = new WechatSMSInfo() ;
							wSMSInfo.setContent(first);
							wSMSInfo.setDivideMoney(moneys[i]);
							wSMSInfo.setTradeNo(userBalancePayment.getTradeNo());
							wSMSInfo.setCompleteTime(DateUtil.dateToString(userBalancePayment.getCompleteTime(), DateUtil.FULL_DATE_NO_SECOND));
							wSMSInfo.setUrl(WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html");
							wSMSInfo.setOpenid(ui.getWeixinOpenid());
							wSMSInfo.setMobilePhone(ui.getMobilePhone());
							wSMSInfo.setUserName(CharSetUtil.strToReplace(ui.getUserName(), 6, "**"));
							wSMSInfo.setTotalIncome(sumDTO.getTotalDivideMoney().toString());
							wSMSInfo.setSendStatus("0");
							wSMSInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
							wSMSInfo.setPaymentId(userBalancePayment.getId());
							wSMSInfo.setUserId(ui.getId());
							wSMSInfo.setPayerName(payer.getUserName());
							wSMSInfo.setPromoterName(promoter==null?null:promoter.getUserName());
							wechatSMSInfoDao.insert(wSMSInfo);
						}
					}
				}
			}
		}else if(typeId == 4){//课程包
			int add_vip_years = 1 ;
			//查询 课程包vip
			CoursePackageVip paramVip = new CoursePackageVip();
			paramVip.setUserId(userId);
			paramVip.setCoursePackageId(userBalancePayment.getPaymentProgramId());
			paramVip.setDisableFlag(0);
			CoursePackageVip vip = coursePackageVipDao.selectByUserIdAndCoursepackageId(paramVip);
			if(null == vip){//第一次购买
				vip = new CoursePackageVip();
				vip.setCoursePackageId(userBalancePayment.getPaymentProgramId());
				vip.setUserId(userId);
				vip.setCreateTime(userBalancePayment.getCompleteTime());
				vip.setDisableFlag(0);
				vip.setIsVipStatus(1);
				vip.setExpireTime(DateUtil.dateAddYears(vip.getCreateTime(),add_vip_years));//添加有效期
                startTime = new Timestamp(vip.getCreateTime().getTime());
                endTime = new Timestamp(vip.getExpireTime().getTime());
                row = coursePackageVipDao.insert(vip);
			}else{//续费
				vip.setIsVipStatus(1);
				if(vip.getExpireTime().getTime() - System.currentTimeMillis() > 0){//现在还没有过期，续有效期
                    startTime = new Timestamp(vip.getExpireTime().getTime());
                    vip.setExpireTime(DateUtil.dateAddYears(vip.getExpireTime(),add_vip_years));
				}else{//期限时间已经过了，则用当前时间去设置
                    startTime = new Timestamp(System.currentTimeMillis());
                    vip.setExpireTime(DateUtil.dateAddYears(new Date(),add_vip_years));
				}
                endTime = new Timestamp(vip.getExpireTime().getTime());
                row = coursePackageVipDao.updateById(vip);
			}
			CoursePackageInfoDTO vo = new CoursePackageInfoDTO();
			vo.setId(userBalancePayment.getPaymentProgramId());
			CoursePackageInfo coursePackageInfo = coursePackageInfoDao.selectById(vo);
			//课程包购买成功，新增一条我的消息
			MessageInfo messageInfo = new MessageInfo();
			messageInfo.setTitle("课程包购买成功");
			messageInfo.setContent("您已成功购买课程包【" + coursePackageInfo.getCoursePackageName() + "】，现在开始抓紧时间学习吧！不然"+ DateUtil.dateToString(vip.getExpireTime(),DateUtil.YEAR_MONTH_DAY) +"就要过期啦");
			messageInfo.setSendTime(new Date());
			messageInfo.setSenderId(1);
			messageInfo.setUserId(userId);
			messageInfo.setReadTag(0);
			messageInfo.setMsgModule(4);//会员开通成功通知
			messageInfo.setCostId(coursePackageInfo.getId());
            messageInfo.setStartTime(startTime);
            messageInfo.setEndTime(endTime);
            messageInfoDao.insert(messageInfo);
			
			//付款成功后，新增推广明细记录
			Map<String , Object> map = insertPromoteDetail(userBalancePayment);
			if(map != null && (int)map.get("err_code") == 0){
				String[] userIds = ((String)map.get("recommendId")).split("@_@");
				String[] moneys = ((String)map.get("divideMoney")).split("@_@");
				UserInfo payer = userInfoDao.queryById(userBalancePayment.getUserId());
				Integer promoterId = (Integer) map.get("promoterId");
				UserInfo promoter = null;
				if (promoterId != null) {
					promoter = userInfoDao.queryById(promoterId);
				}
				for (int i = 0; i< userIds.length; i++) {
					UserInfo ui = userInfoDao.queryById(Integer.parseInt(userIds[i]));
					if(ui !=null ){
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String first = "您有一笔365家长课堂推广收入，请笑纳";
						//判断当前时间是否在06:00-23:00，如果不是，把消息体保存到数据表，等6点统一发送；否则及时发
						if(DateUtil.betweenTime()){
							if( StringUtils.isNotBlank(ui.getWeixinOpenid())){
								WeChatUtil.sendWechatTemplateMessageIncome(first ,moneys[i]
										, userBalancePayment.getTradeNo() ,sdf.format(userBalancePayment.getCompleteTime())
										, WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html"
										, ui.getWeixinOpenid());
							}
							
							if(StringUtils.isNotBlank(ui.getMobilePhone())){
								//给推广人发短信通知
								Map<String , Object> smsParamMap = new HashMap<String , Object>();
								smsParamMap.put("name", CharSetUtil.strToReplace(ui.getUserName(), 6, "**"));
								smsParamMap.put("income", moneys[i]);
								if (promoter != null) {
									smsParamMap.put("pro", CharSetUtil.strToReplace(promoter.getUserName(), 6, "**"));
								}
								smsParamMap.put("payer", CharSetUtil.strToReplace(payer.getUserName(), 6, "**"));
								smsParamMap.put("time", DateUtil.dateToString(userBalancePayment.getCompleteTime(), DateUtil.FULL_DATE_NO_SECOND));
//								PromoteDetailDTO dto = new PromoteDetailDTO() ;
//								dto.setRecommendId(ui.getId());
//								PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
//								if(sumDTO != null){
//									smsParamMap.put("total", sumDTO.getTotalDivideMoney()) ;
//								}else{
//									smsParamMap.put("total", "") ;
//								}
								//一般情况最多发送两条短信
								//第一条短信是一级推广，第二条是二级推广
								if (i == 0 || promoter == null) {
									smsSendInfoBo.sendSMSAndAddRecord(ui.getMobilePhone(), smsParamMap
											, SMSTemplate.TEMPLATE_11, "2", "0");
								}else {
									smsSendInfoBo.sendSMSAndAddRecord(ui.getMobilePhone(), smsParamMap
											, SMSTemplate.TEMPLATE_12, "2", "0");
								}
							}
						}else{
							PromoteDetailDTO dto = new PromoteDetailDTO() ;
							dto.setRecommendId(ui.getId());
							PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
							
							WechatSMSInfo wSMSInfo = new WechatSMSInfo() ;
							wSMSInfo.setContent(first);
							wSMSInfo.setDivideMoney(moneys[i]);
							wSMSInfo.setTradeNo(userBalancePayment.getTradeNo());
							wSMSInfo.setCompleteTime(sdf.format(userBalancePayment.getCompleteTime()));
							wSMSInfo.setUrl(WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html");
							wSMSInfo.setOpenid(ui.getWeixinOpenid());
							wSMSInfo.setMobilePhone(ui.getMobilePhone());
							wSMSInfo.setUserName(CharSetUtil.strToReplace(ui.getUserName(), 6, "**"));
							wSMSInfo.setTotalIncome(sumDTO.getTotalDivideMoney().toString());
							wSMSInfo.setSendStatus("0");
							wSMSInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
							wSMSInfo.setPaymentId(userBalancePayment.getId());
							wSMSInfo.setUserId(ui.getId());
							wSMSInfo.setPayerName(payer.getUserName());
							wSMSInfo.setPromoterName(promoter==null?null:promoter.getUserName());
							wechatSMSInfoDao.insert(wSMSInfo);
						}
					}
				}
			}
			
			//新增需求 获得积分
			IntegralInfo intetral = IntegralUtil.setIntegral(userId
					, (int)(IntegralEnum.BUY_COURSE.getScore()*money)
					, IntegralEnum.BUY_COURSE.getTypeDesc(), IntegralEnum.BUY_COURSE.getTypeId()
					, userBalancePayment.getId()); 

            //购买成功后,添加缓存  格式如(key:"user_video_vip_3173" value:"8,17,23")
            List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectVideoListById(coursePackageInfo);
            String vids = redisPool.get(GlobalConstant.USER_VIDEO_VIP + userId); //用户拥有观看权限的视频 ("8,17,23")
            if (StringUtils.isBlank(vids)) {
                vids = "";
            }
            for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
                //如果用户没有该单节微课的观看权限,就往缓存的value后追加
				if (!RedisUtil.isVideoVip(userId, coursePackageInfoDTO.getVideoId())) {
					vids += (coursePackageInfoDTO.getVideoId() + ",");
				}
			}
            redisPool.set(GlobalConstant.USER_VIDEO_VIP + userId, vids);

        } else if (typeId == 5) { //升级分销商支付金额
            //查询正在升级的那条记录   (isUpgrating=0,disableFlag=1)
            DistributorInfoDTO distributorInfoDTO = distributorInfoDao.queryByIdNoDisableFlag(userBalancePayment.getPaymentProgramId());

            if (distributorInfoDTO != null) {
                DistributorInfo distributorInfo = new DistributorInfo();
				if(distributorInfoDTO.getFuCardNum() >= 20 && distributorInfoDTO.getFuCardNum() < 50){
					distributorInfo.setDistributorType("1");//中级分销商
					distributorInfo.setSharingProportion(SharingProportionEnum.MIDDLE_DISTRIBUTOR.getSharingProportion());//默认分成比例为25%
				}else if(distributorInfoDTO.getFuCardNum()>= 50){
					distributorInfo.setDistributorType("2");//高级分销商
					distributorInfo.setSharingProportion(SharingProportionEnum.HIGHT_DISTRIBUTOR.getSharingProportion());//默认分成比例为40%
				}
				distributorInfo.setId(distributorInfoDTO.getId());
				//升级时间
				distributorInfo.setUpgradeTime(new Timestamp(System.currentTimeMillis()));
				//有效期是当前时间加一年
				distributorInfo.setDeadlineTime(new Timestamp(DateUtil.dateTimeAddYears(System.currentTimeMillis(), 1)));
				distributorInfo.setIsUpgrading("1");//设置是否正在升级中为否，即值为1
				distributorInfo.setDisabledFlag(0);
				row = distributorInfoDao.updateById(distributorInfo);
			}
        } else if (typeId == 6 || typeId == 8) {//提问导师
            //插入明细表里面
            Integer paymentProgramId = userBalancePayment.getPaymentProgramId();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (paymentProgramId == null) return false;
            if (typeId == 8) {
                QuestionInfo questionInfo = new QuestionInfo();
                questionInfo.setId(paymentProgramId);
                questionInfo.setDisableFlag(0);
                row = questionInfoDao.updateById(questionInfo);
                if (row > 0) {
                    //积分添加
                    IntegralInfo integral = IntegralUtil.setIntegral(userBalancePayment.getUserId()
                            , IntegralEnum.ASK.getScore()
                            , IntegralEnum.ASK.getTypeDesc()
                            , IntegralEnum.ASK.getTypeId()
                            , paymentProgramId);

                    //爱值添加
                    HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(userBalancePayment.getUserId()
                            , HappinessInfoEnum.ASK.getLoveValue(), HappinessInfoEnum.ASK.getTypeDesc()
                            , HappinessInfoEnum.ASK.getTypeId(), "0", paymentProgramId);
                    happinessInfoDao.insert(hi);
                }

                //根据问题的id查询邀请人的Id
                QuestionInfo  question = questionInfoDao.queryById(questionInfo);
                //语音提问成功，新增一条我的消息
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setTitle("支付语音提问成功");
                messageInfo.setContent("您已成功向明师发起语音提问，请耐心等候明师的回答");
                messageInfo.setSendTime(new Timestamp(System.currentTimeMillis()));
                messageInfo.setSenderId(1);
                messageInfo.setUserId(userId);
                messageInfo.setReadTag(0);
                messageInfo.setCostId(question.getInvitedPersonId());
                messageInfo.setMsgModule(3);//语音提问成功

                //语音提问成功，向导师推送消息
                QuestionInfo questionInfo1 = questionInfoDao.queryById(questionInfo);
                UserInfo teacherUserInfo = userInfoDao.queryById(questionInfo1.getInvitedPersonId());

                if (teacherUserInfo.getWeixinOpenid() == null) {
                    return false;
                }
                Map dataMap = new HashMap();
                dataMap.put("first", questionInfo1.getUserName() + "向您付费提了一个问题");
                dataMap.put("keyword1", sdf.format(userBalancePayment.getCompleteTime()));
                dataMap.put("keyword2", "家庭·生命教育");
                dataMap.put("keyword3", questionInfo1.getQuestionContent());
                dataMap.put("remark", "马上回答，获得收入。被人偷听还有分成。");
                TemplateMessage message = new TemplateMessage();
                message.setSendType("6");
                message.setOpenid(teacherUserInfo.getWeixinOpenid());
                message.setDataMap(dataMap);

                String url = WxConsts.PUBLIC_DOMAIN + "/index.html?from=weQA/record_anwser.html@_@id=" + questionInfo1.getId();
                message.setUrl(url);

                messageInfoDao.insert(messageInfo);
                WeChatUtil.sendWechatTemplateMessage(message);
            } else if (typeId == 6) {
                QuestionComment newQuestionComment = new QuestionComment();
                newQuestionComment.setQuestionId(paymentProgramId);
                QuestionComment questionComment = questionCommentDao.queryCommentInfoByQid(newQuestionComment);

                //插入盈利表
                Integer commentedId = questionComment.getCommentedId();
                Integer userId1 = questionComment.getUserId();

                RecordIncomeInfo recordIncomeInfo = new RecordIncomeInfo();
                recordIncomeInfo.setPaymentId(userBalancePayment.getId());
                recordIncomeInfo.setRegisterDate(new Timestamp(System.currentTimeMillis()));
                recordIncomeInfo.setCostName("回答被听");
                recordIncomeInfo.setCostTypeId(3);
                recordIncomeInfo.setMoney(BigDecimal.valueOf(money).divide(new BigDecimal(2), 2, BigDecimal.ROUND_UP));
                recordIncomeInfo.setSettleStatus(1);
                recordIncomeInfo.setBeneficiaryId(userId1);//回答者
                recordIncomeInfoDao.insert(recordIncomeInfo);
                {
                    recordIncomeInfo.setCostTypeId(2);
                    recordIncomeInfo.setCostName("提问被听");
                    recordIncomeInfo.setBeneficiaryId(commentedId);//提问者
                    recordIncomeInfoDao.insert(recordIncomeInfo);
                }

                //语音提问成功，新增一条我的消息
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setTitle("支付语音偷听成功");
                messageInfo.setContent("您可以偷听该明师的语音回答了");
                messageInfo.setSendTime(new Timestamp(System.currentTimeMillis()));
                messageInfo.setSenderId(1);
                messageInfo.setUserId(userId);
                messageInfo.setReadTag(0);
                messageInfo.setMsgModule(3);//语音提问成功

                //语音提问成功，向导师推送消息
                QuestionInfo questionInfo = new QuestionInfo();
                questionInfo.setId(questionComment.getQuestionId());
                QuestionInfo questionInfo1 = questionInfoDao.queryById(questionInfo);
                UserInfo teacherUserInfo = userInfoDao.queryById(questionInfo1.getInvitedPersonId());

                if (teacherUserInfo.getWeixinOpenid() == null) {
                    messageInfoDao.insert(messageInfo);
                    return false;
                }
                messageInfoDao.insert(messageInfo);
            } else if (userBalancePayment.getName().equals("提问被听")) {
                //这个 理论 存在 ，实际不存在
//                costTypeId=3;
            } else {
                return false;
            }
        }else if (typeId == 9) { //微课
			int add_vip_years = 1 ;
			//查询 微课vip
			VideoVip paramVip = new VideoVip();
			paramVip.setUserId(userId);
			paramVip.setVideoId(userBalancePayment.getPaymentProgramId());
			paramVip.setDisableFlag(0);
			VideoVip vip = videoVipDao.selectByUserIdAndVideoId(paramVip);
			if(null == vip){//第一次购买
				vip = new VideoVip();
				vip.setVideoId(userBalancePayment.getPaymentProgramId());
				vip.setUserId(userId);
				vip.setCreateTime(userBalancePayment.getCompleteTime());
				vip.setDisableFlag(0);
				vip.setIsVipStatus(1);
				vip.setExpireTime(DateUtil.dateAddYears(vip.getCreateTime(),add_vip_years));//添加有效期
                startTime = new Timestamp(vip.getCreateTime().getTime());
                endTime = new Timestamp(vip.getExpireTime().getTime());
                row = videoVipDao.insert(vip);
			}else{//续费
				vip.setIsVipStatus(1);
				if(vip.getExpireTime().getTime() - System.currentTimeMillis() > 0){//现在还没有过期，续有效期
                    startTime = new Timestamp(vip.getExpireTime().getTime());
                    vip.setExpireTime(DateUtil.dateAddYears(vip.getExpireTime(),add_vip_years));
				}else{//期限时间已经过了，则用当前时间去设置
                    startTime = new Timestamp(System.currentTimeMillis());
                    vip.setExpireTime(DateUtil.dateAddYears(new Date(),add_vip_years));
				}
                endTime = new Timestamp(vip.getExpireTime().getTime());
                row = videoVipDao.updateById(vip);
			}
			VideoInfo videoInfo = (VideoInfo) videoInfoDao.queryById(userBalancePayment.getPaymentProgramId());
			//课程包购买成功，新增一条我的消息
			MessageInfo messageInfo = new MessageInfo();
			messageInfo.setTitle("微课购买成功");
			messageInfo.setContent("恭喜您，您已成功购买微课【" + videoInfo.getVideoName() + "】，有效期至"+ DateUtil.dateToString(vip.getExpireTime(),DateUtil.YEAR_MONTH_DAY));
			messageInfo.setSendTime(new Date());
			messageInfo.setSenderId(1);
			messageInfo.setUserId(userId);
			messageInfo.setReadTag(0);
			messageInfo.setMsgModule(6);//会员开通成功通知
			messageInfo.setCostId(videoInfo.getId());
            messageInfo.setStartTime(startTime);
            messageInfo.setEndTime(endTime);
            messageInfoDao.insert(messageInfo);
			
			//付款成功后，新增推广明细记录
			Map<String , Object> map = insertPromoteDetail(userBalancePayment);
			if(map != null && (int)map.get("err_code") == 0){
				String[] userIds = ((String)map.get("recommendId")).split("@_@");
				String[] moneys = ((String)map.get("divideMoney")).split("@_@");
				UserInfo payer = userInfoDao.queryById(userBalancePayment.getUserId());
				Integer promoterId = (Integer) map.get("promoterId");
				UserInfo promoter = null;
				if (promoterId != null) {
					promoter = userInfoDao.queryById(promoterId);
				}
				for (int i = 0; i< userIds.length; i++) {
					UserInfo ui = userInfoDao.queryById(Integer.parseInt(userIds[i]));
					if(ui !=null ){
						if( StringUtils.isNotBlank(ui.getWeixinOpenid())){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String first = "您有一笔365家长课堂推广收入，请笑纳";
							//判断当前时间是否在06:00-23:00，如果不是，把消息体保存到数据表，等6点统一发送；否则及时发
							if(DateUtil.betweenTime()){
								if( StringUtils.isNotBlank(ui.getWeixinOpenid())){
									WeChatUtil.sendWechatTemplateMessageIncome(first ,moneys[i]
											, userBalancePayment.getTradeNo() ,sdf.format(userBalancePayment.getCompleteTime())
											, WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html"
											, ui.getWeixinOpenid());
								}
								
								if(StringUtils.isNotBlank(ui.getMobilePhone())){
									//给推广人发短信通知
									Map<String , Object> smsParamMap = new HashMap<String , Object>();
									smsParamMap.put("name", CharSetUtil.strToReplace(ui.getUserName(), 6, "**"));
									smsParamMap.put("income", moneys[i]);
									if (promoter != null) {
										smsParamMap.put("pro", CharSetUtil.strToReplace(promoter.getUserName(), 6, "**"));
									}
									smsParamMap.put("payer", CharSetUtil.strToReplace(payer.getUserName(), 6, "**"));
									smsParamMap.put("time", DateUtil.dateToString(userBalancePayment.getCompleteTime(), DateUtil.FULL_DATE_NO_SECOND));
//									PromoteDetailDTO dto = new PromoteDetailDTO() ;
//									dto.setRecommendId(ui.getId());
//									PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
//									if(sumDTO != null){
//										smsParamMap.put("total", sumDTO.getTotalDivideMoney()) ;
//									}else{
//										smsParamMap.put("total", "") ;
//									}
									if (i == 0 || promoter == null) {
										smsSendInfoBo.sendSMSAndAddRecord(ui.getMobilePhone(), smsParamMap
												, SMSTemplate.TEMPLATE_11, "2", "0");
									}else {
										smsSendInfoBo.sendSMSAndAddRecord(ui.getMobilePhone(), smsParamMap
												, SMSTemplate.TEMPLATE_12, "2", "0");
									}
								}
							}else{
								PromoteDetailDTO dto = new PromoteDetailDTO() ;
								dto.setRecommendId(ui.getId());
								PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
								
								WechatSMSInfo wSMSInfo = new WechatSMSInfo() ;
								wSMSInfo.setContent(first);
								wSMSInfo.setDivideMoney(moneys[i]);
								wSMSInfo.setTradeNo(userBalancePayment.getTradeNo());
								wSMSInfo.setCompleteTime(sdf.format(userBalancePayment.getCompleteTime()));
								wSMSInfo.setUrl(WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html");
								wSMSInfo.setOpenid(ui.getWeixinOpenid());
								wSMSInfo.setMobilePhone(ui.getMobilePhone());
								wSMSInfo.setUserName(CharSetUtil.strToReplace(ui.getUserName(), 6, "**"));
								wSMSInfo.setTotalIncome(sumDTO.getTotalDivideMoney().toString());
								wSMSInfo.setSendStatus("0");
								wSMSInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
								wSMSInfo.setPaymentId(userBalancePayment.getId());
								wSMSInfo.setUserId(ui.getId());
								wSMSInfo.setPayerName(payer.getUserName());
								wSMSInfo.setPromoterName(promoter==null?null:promoter.getUserName());
								wechatSMSInfoDao.insert(wSMSInfo);
							}
						}
					}
				}
			}
			
			//新增需求 获得积分
			IntegralInfo intetral = IntegralUtil.setIntegral(userId
					, (int)(IntegralEnum.BUY_VIDEO.getScore()*money)
					, IntegralEnum.BUY_VIDEO.getTypeDesc(), IntegralEnum.BUY_VIDEO.getTypeId()
					, userBalancePayment.getId()); 
			
			//购买成功后,添加缓存  格式如(key:"user_video_vip_3173" value:"8,17,23")
			String vids = redisPool.get(GlobalConstant.USER_VIDEO_VIP+userId); //用户拥有观看权限的视频 ("8,17,23")
			if (StringUtils.isBlank(vids)) {
				vids="";
			}
			//如果用户没有该单节微课的观看权限,就往缓存的value后追加
			if (!RedisUtil.isVideoVip(userId, userBalancePayment.getPaymentProgramId())) {
				vids += (userBalancePayment.getPaymentProgramId() + ",");
			}
			redisPool.set(GlobalConstant.USER_VIDEO_VIP+userId, vids);
			
		}else if (typeId == 10) {
			//扣积分
			IntegralInfo intetral = IntegralUtil.setIntegral(userId, -userBalancePayment.getIntegral()
					, IntegralEnum.BUY_ACTIVITY.getTypeDesc()
					, IntegralEnum.BUY_ACTIVITY.getTypeId(), userBalancePayment.getPaymentProgramId());

			//插入活动报名表
			ActivitySignupInfo signupInfo = new ActivitySignupInfo();
			signupInfo.setActivityId(userBalancePayment.getPaymentProgramId());
			signupInfo.setUserId(userId);
			signupInfo.setAmount(userBalancePayment.getAmount());
			signupInfo.setPaymentId(userBalancePayment.getId());
			signupInfo.setPaymentCode(userBalancePayment.getCode());
			activitySignupInfoDao.insertSelective(signupInfo);
			//微信模板通知(付费人/报名人)
			/*UserInfo payer = userInfoDao.queryById(userBalancePayment.getUserId());
			if(payer !=null && StringUtils.isNotBlank(payer.getWeixinOpenid())){
				
			}*/
			//付款成功后，新增推广明细记录
			Map<String , Object> map = insertPromoteDetail(userBalancePayment);
			if(map != null && (int)map.get("err_code") == 0){
				String[] userIds = ((String)map.get("recommendId")).split("@_@");
				String[] moneys = ((String)map.get("divideMoney")).split("@_@");
				
				for (int i = 0; i< userIds.length; i++) {
					UserInfo ui = userInfoDao.queryById(Integer.parseInt(userIds[i]));
					if(ui !=null ){
						if( StringUtils.isNotBlank(ui.getWeixinOpenid())){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String first = "您有一笔365家长课堂推广收入，请笑纳";
							if( StringUtils.isNotBlank(ui.getWeixinOpenid())){
								WeChatUtil.sendWechatTemplateMessageIncome(first ,moneys[i]
										, userBalancePayment.getTradeNo() ,sdf.format(userBalancePayment.getCompleteTime())
										, WxConsts.PUBLIC_DOMAIN + "/index.html?from=distributor/distributor.html"
										, ui.getWeixinOpenid());
							}
						}
					}
				}
			}
		}
		//如果使用了代金券,将代金券设置为已使用
		if (userBalancePayment.getVoucherId()!=null) {
			IntegralExchangedLog log = new IntegralExchangedLog();
			log.setId(userBalancePayment.getVoucherId());
			log.setIsUse(1);//已使用
			integralExchangedLogDao.updateById(log);
		}
		
        if (row != 1) {
            return false;
		}else {
			return true;
		}
	}
	
	/**
	 * TODO 没有进行事务处理
	 * 发送消息
	 * 
	 * @param userBalancePayment   订单
	 */
	private void txSendMsg(UserBalancePayment userBalancePayment) {
		UserBalanceInfo userBalanceInfo = userBalanceInfoDao.queryByUserId(userBalancePayment.getUserId());
		int typeId = userBalancePayment.getTypeId();
		float money = userBalancePayment.getMoney();
		MessageInfo messageInfo = new MessageInfo();
		
		DecimalFormat decimalFormat = new DecimalFormat(".00");
		if (typeId==1) {
			messageInfo.setTitle("余额充值信息");
			messageInfo.setContent("你充值"+ decimalFormat.format(money)  +"元成功，当前余额为" + decimalFormat.format(userBalanceInfo.getMoney())+"元。");
			messageInfo.setSendTime(new Date());
			messageInfo.setSenderId(1);
			messageInfo.setUserId(userBalancePayment.getUserId());
			messageInfo.setReadTag(0);
			messageInfo.setMsgModule(1);
		}else if(typeId== 2) {
			UserMemberInfo userMemberInfo = new UserMemberInfo();
			userMemberInfo.setUserId(userBalancePayment.getUserId());
			userMemberInfo.setGradeId(userBalancePayment.getGradeId());
			userMemberInfo = userMemberInfoDao.queryBySelected(userMemberInfo).get(0);
			messageInfo.setTitle("会员开通信息");
			String content = "你的会员套餐（"+ userBalancePayment.getName() +"）已购买成功，会员费用为"+decimalFormat.format(money) +"元，会员到期时间为"+DateUtil.longToString(userMemberInfo.getEndDate(), DateUtil.YEAR_MONTH_DAY) + "。";
			messageInfo.setContent(content);
			messageInfo.setSendTime(new Date());
			messageInfo.setSenderId(1);
			messageInfo.setUserId(userBalancePayment.getUserId());
			messageInfo.setReadTag(0);
			messageInfo.setMsgModule(1);
		}
		messageInfoDao.insert(messageInfo);
	}
	
	/**
	 * TODO 没有进行事务处理
	 * 发送短信通知
	 */
	private void sendSMSToStudent(SMSSendDto smsSendDto){
		String uniqueFlag = "";
		if (smsSendDto.getUniqueFlag() != null) {
			uniqueFlag = smsSendDto.getUniqueFlag();
		}
		String smsType = "normal";
		String smsFreeSignName = SMSUtil.SIGN_NAME[0];
		SMSTemplate sms = SMSTemplate.TEMPLATE_02;	
		Map<String, Object> smsParamMap = new HashMap<String, Object>();		
		smsParamMap.put("name", smsSendDto.getProduct());
		smsParamMap.put("code", smsSendDto.getCode());
		smsParamMap.put("passwod",smsSendDto.getPassword());	
		SMSSendReqInfo smsSendReq = new SMSSendReqInfo(smsType,
				smsFreeSignName, smsParamMap, smsSendDto.getRecNum(), sms);

		Map<String, Object> map = SMSUtil.sendSMS(smsSendReq);
		if (map.get("responseCode") == ResponseCode.SUCCESS.getCode()) {
			
			// 插入一条信息记录
			JSONObject jsonObject = JSONObject.fromObject(map
					.get("responseDesc"));
			jsonObject = JSONObject.fromObject(jsonObject
					.getString("alibaba_aliqin_fc_sms_num_send_response"));
			jsonObject = JSONObject.fromObject(jsonObject.getString("result"));				
			SMSSendInfo smsSendInfo = new SMSSendInfo(); 
			smsSendInfo.setSmsCode(sms.getTemplateID());
			smsSendInfo.setRecNum(smsSendDto.getRecNum());
			smsSendInfo.setSendCode(smsSendDto.getCode());
			smsSendInfo.setUniqueFlag(uniqueFlag);
			try {
				SimpleDateFormat sim = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String dateStr = DateUtil.dateToString(new Date(),
						DateUtil.FULL_DATE);
				Date smsSendTime = sim.parse(dateStr);
				smsSendInfo.setSmsSendTime(smsSendTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}			
			smsSendInfo.setSmsStatus("2");
			smsSendInfo.setSmsCode("SMS_16440023");
			smsSendInfo.setBizCode(jsonObject.getString("model"));
			smsSendInfoDao.insert(smsSendInfo);
		}
	}
	
	
	/**
	 * 发送短信通知
	 */
	private void sendSMSToTeacher(SMSSendDto smsSendDto){
		String uniqueFlag = "";
		if (smsSendDto.getUniqueFlag() != null) {
			uniqueFlag = smsSendDto.getUniqueFlag();
		}
		String smsType = "normal";
		String smsFreeSignName = SMSUtil.SIGN_NAME[0];
		SMSTemplate sms = SMSTemplate.TEMPLATE_03;	
		Map<String, Object> smsParamMap = new HashMap<String, Object>();		
		smsParamMap.put("tname", smsSendDto.getTname());
		smsParamMap.put("sname", smsSendDto.getSname());
		smsParamMap.put("time",DateUtil.dateToString(new Date(), 2));	
		smsParamMap.put("product", smsSendDto.getProduct());
		SMSSendReqInfo smsSendReq = new SMSSendReqInfo(smsType,
				smsFreeSignName, smsParamMap, smsSendDto.getRecNum(), sms);

		Map<String, Object> map = SMSUtil.sendSMS(smsSendReq);
		if (map.get("responseCode") == ResponseCode.SUCCESS.getCode()) {
			
			// 插入一条信息记录
			JSONObject jsonObject = JSONObject.fromObject(map
					.get("responseDesc"));
			jsonObject = JSONObject.fromObject(jsonObject
					.getString("alibaba_aliqin_fc_sms_num_send_response"));
			jsonObject = JSONObject.fromObject(jsonObject.getString("result"));				
			SMSSendInfo smsSendInfo = new SMSSendInfo(); 
			smsSendInfo.setSmsCode(sms.getTemplateID());
			smsSendInfo.setRecNum(smsSendDto.getRecNum());
			smsSendInfo.setSendCode(smsSendDto.getCode());
			smsSendInfo.setUniqueFlag(uniqueFlag);
			try {
				SimpleDateFormat sim = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String dateStr = DateUtil.dateToString(new Date(),
						DateUtil.FULL_DATE);
				Date smsSendTime = sim.parse(dateStr);
				smsSendInfo.setSmsSendTime(smsSendTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}			
			smsSendInfo.setSmsStatus("2");
			smsSendInfo.setSmsCode("SMS_34330133");
			smsSendInfo.setBizCode(jsonObject.getString("model"));
			smsSendInfoDao.insert(smsSendInfo);
		}
	}
	
	@Override
	public Object getOrderListByPage(UserBalancePayment userBalancePayment,UserInfo userInfo){
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == userInfo ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if (!"".equals(userBalancePayment.getStartTimeString())
					&& userBalancePayment.getStartTimeString() != null) {
				userBalancePayment.setStartTime(sim.parse(userBalancePayment
						.getStartTimeString()));
			}
			if (!"".equals(userBalancePayment.getEndTimeString())
					&& userBalancePayment.getEndTimeString() != null) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(sim.parse(userBalancePayment.getEndTimeString()));
				cal.add(Calendar.DATE, 1);
				userBalancePayment.setEndTime(cal.getTime());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		String payMethod = userBalancePayment.getPaymentMethod();
		if ("0".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("");
		}else if ("1".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("alipay");
		}else if ("2".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("wxqrpay");
		}else if ("3".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("balance");
		}else {
			userBalancePayment.setPaymentMethod(null);
		}
		
		int total = userBalancePaymentDao.getTotalPaymentCount(userBalancePayment);
		List<UserBalancePayment> userBalancePayments = null;
		if(total > 0){
			userBalancePayments = userBalancePaymentDao.queryPaymentByPage(userBalancePayment);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (UserBalancePayment u : userBalancePayments) {
				u.setOrderTimeString(format.format(u.getOrderTime()));
				if (u.getCompleteTime() != null) {
					u.setCompleteTimeString(format.format(u.getCompleteTime()));
				} else {
					u.setCompleteTimeString("— —");
				}
				if ("alipay".equals(u.getPaymentMethod())) {
					u.setPaymentMethod("支付宝支付");
				} else if ("wxqrpay".equals(u.getPaymentMethod())) {
					u.setPaymentMethod("微信支付");
				}else if ("balance".equals(u.getPaymentMethod())) {
					u.setPaymentMethod("余额支付");
				}
			}
		}
        int totalCount = userBalancePaymentDao.getTotalCount(userBalancePayment);
        int totalMoney = userBalancePaymentDao.getTotalMoney(userBalancePayment);
        int totalPayMoney = userBalancePaymentDao.getTotalPayMoney(userBalancePayment);
        int totalPayCount = userBalancePaymentDao.getTotalPayCount(userBalancePayment);
        map.put("totalCount", totalCount); //全站订单总数量
		map.put("totalMoney", totalMoney);  //全站订单总金额
		map.put("totalPayCount", totalPayCount);  //全站已付订单数
		map.put("totalPayMoney", totalPayMoney);  //全站已付订单总金额
		map.put("rows", userBalancePayments);
		map.put("total", total);
		return map;
	}

	@Override
	public Object getOrderStatus() {
		List<OrderStatusInfo> list = orderStatusInfoDao.orderStatusInfoList();
		for(int i=0;i<list.size();i++){
			list.get(i).setText(list.get(i).getName());
		}
		return list;
	}

	@Override
	public Object exportPaymentList(HttpServletResponse response,UserBalancePayment userBalancePayment,
			UserInfo userInfo) {
		if (userInfo == null) {
			return "userInfo_error";
		}
		
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if (!"".equals(userBalancePayment.getStartTimeString())
					&& userBalancePayment.getStartTimeString() != null) {
				userBalancePayment.setStartTime(sim.parse(userBalancePayment
						.getStartTimeString()));
			}
			if (!"".equals(userBalancePayment.getEndTimeString())
					&& userBalancePayment.getEndTimeString() != null) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(sim.parse(userBalancePayment.getEndTimeString()));
				cal.add(Calendar.DATE, 1);
				userBalancePayment.setEndTime(cal.getTime());
			}
		} catch (ParseException e) {
//			e.printStackTrace();
		}
		String payMethod = userBalancePayment.getPaymentMethod();
		if ("0".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("");
		}else if ("1".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("alipay");
		}else if ("2".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("wxqrpay");
		}else if ("3".equals(payMethod)) {
			userBalancePayment.setPaymentMethod("balance");
		}else {
			userBalancePayment.setPaymentMethod(null);
		}
		if (userBalancePayment.getStatusId() != null && userBalancePayment.getStatusId() != 1 && userBalancePayment.getStatusId() != 2) {
			userBalancePayment.setStatusId(null);	
		}
		
		OutputStream out = null;
		String sheetName = "";
		if (userBalancePayment.getTypeId().intValue() ==1) {
			sheetName = "余额充值";
			
			try {
				String fileName =  "订单列表-" + sheetName
						+ DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)
						+ ".xls";
				response.setContentType("multipart/form-data");
				response.setHeader("Content-Disposition", "attachment;fileName="
						+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));
				out = response.getOutputStream();
			} catch (IOException e) {
//				e.printStackTrace();
			}
			
			List<BalanceRechargeDto> list = userBalancePaymentDao.queryExportRechargeList(userBalancePayment);
			for (BalanceRechargeDto dto : list) {
				String method =  dto.getPaymentMethod();
				if ("alipay".equals(method)) {
					dto.setPaymentMethod("支付宝支付");
				}else if ("wxqrpay".equals(method)) {
					dto.setPaymentMethod("微信支付");
				}else if ("balance".equals(method)) {
					dto.setPaymentMethod("余额支付");
				}else {
					dto.setPaymentMethod("未支付");
				}
			}
			
			String[] headers = {"订单号","订单名称","价格（元）","完成时间","支付方式","用户姓名","用户手机号"};
			ExportExcelUtil<BalanceRechargeDto> ex = new ExportExcelUtil<BalanceRechargeDto>();
			ex.exportExcel(sheetName, headers, list, out);
		}else if(userBalancePayment.getTypeId().intValue() ==2){
			sheetName = "会员开通与续约";
			try {
				String fileName =  "订单列表-" + sheetName
						+ DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)
						+ ".xls";
				response.setContentType("multipart/form-data");
				response.setHeader("Content-Disposition", "attachment;fileName="
						+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));
				out = response.getOutputStream();
			} catch (IOException e) {
//				e.printStackTrace();
			}
			
			List<OrderListDto> list = userBalancePaymentDao.queryExportOrderList(userBalancePayment);
			for (OrderListDto dto : list) {
				String method =  dto.getPaymentMethod();
				if ("alipay".equals(method)) {
					dto.setPaymentMethod("支付宝支付");
				}else if ("wxqrpay".equals(method)) {
					dto.setPaymentMethod("微信支付");
				}else if ("balance".equals(method)) {
					dto.setPaymentMethod("余额支付");
				}else {
					dto.setPaymentMethod("未支付");
				}
			}
			
			String[] headers = {"订单号","订单名称","价格（元）","完成时间","支付方式","用户姓名","用户手机号","推荐人","年级选择","所在城市"};
			ExportExcelUtil<OrderListDto> ex = new ExportExcelUtil<OrderListDto>();
			ex.exportExcel(sheetName, headers, list, out);
		}else if(userBalancePayment.getTypeId().intValue() == 3){
			sheetName = "福卡激活";
			try {
				String fileName =  "订单列表-" + sheetName
						+ DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)
						+ ".xls";
				response.setContentType("multipart/form-data");
				response.setHeader("Content-Disposition", "attachment;fileName="
						+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));
				out = response.getOutputStream();
			} catch (IOException e) {
//				e.printStackTrace();
			}
			
			List<OrderListDto> list = userBalancePaymentDao.querySaleCardList(userBalancePayment);
			
			
			String[] headers = {"用户姓名","用户手机号","完成时间"};
			ExportExcelUtil<OrderListDto> ex = new ExportExcelUtil<OrderListDto>();
			ex.exportExcel(sheetName, headers, list, out);
		}else {
			return null;
		}
		return null;
	}

	@Override
	public List<UserBalancePayment> getPayMethodList() {
		List<UserBalancePayment> lPayments = new ArrayList<UserBalancePayment>();
		String[] methods = {"全部","支付宝支付","微信支付","余额支付"};
		for (int i = 0; i < methods.length; i++) {
			UserBalancePayment userBalancePayment = new UserBalancePayment();
			userBalancePayment.setId(i);
			userBalancePayment.setText(methods[i]);
			lPayments.add(userBalancePayment);
		}
		return lPayments;
	}

	@Override
	public String checkPaymentNoGrade(UserInfo userInfo) {
		if (userInfo == null) {
			return "userInfo_error";
		}
		UserBalancePayment userBalancePayment = new UserBalancePayment();
		userBalancePayment.setUserId(userInfo.getId());		
		int payNum=userBalancePaymentDao.queryHadPaymentByUserId(userBalancePayment).size();
		UserMemberInfo userMemberInfo = new UserMemberInfo();
		userMemberInfo.setUserId(userInfo.getId());
		int userNum = userMemberInfoDao.queryBySelected(userMemberInfo).size();
		if(payNum>0 || userNum>0){
			userBalancePayment = userBalancePaymentDao.queryPaymentForNoGrade(userBalancePayment);
			if (userBalancePayment != null) {
				updateGrade(userBalancePayment, userInfo);
				return "error";
			}else {
				return "ok";
			}
		}else{
			return "noPay";
		}
	}
	
	
	public void updateGrade(UserBalancePayment userBalancePayment,UserInfo userInfo){
		//更新订单表中的年级
		userBalancePayment.setGradeId(38);//改---使用一年级表示购买所有年级
		userBalancePaymentDao.updatePayment(userBalancePayment);
		
		UserMemberInfo userMemberInfo = new UserMemberInfo();
		userMemberInfo.setGradeId(38);//改---使用一年级表示购买所有年级
		//检查年级套餐表中是否有数据
		userMemberInfo.setUserId(userInfo.getId());
		//userMemberInfo.setGradeId(gradeInfo.getId());
		List<UserMemberInfo> userMemberInfos = userMemberInfoDao.queryBySelected(userMemberInfo);
		Calendar calendar = Calendar.getInstance();
		if (userMemberInfos == null || userMemberInfos.size()==0) {
			//无数据
			Date today = userBalancePayment.getCompleteTime();
			calendar.setTime(today);
			calendar.add(Calendar.YEAR, 1);
			calendar.add(Calendar.DATE, -1);
			userMemberInfo.setStartDate(today.getTime());
			userMemberInfo.setEndDate(calendar.getTime().getTime());
			userMemberInfo.setMembershipFlag(1);
			userMemberInfoDao.insert(userMemberInfo);
		}else if (userMemberInfos.get(0).getMembershipFlag().intValue()==0) {
			//有数据但是过期
			userMemberInfo.setId(userMemberInfos.get(0).getId());
			Date today = userBalancePayment.getCompleteTime();
			calendar.setTime(today);
			calendar.add(Calendar.YEAR, 1);
			calendar.add(Calendar.DATE, -1);
			userMemberInfo.setStartDate(today.getTime());
			userMemberInfo.setEndDate(calendar.getTime().getTime());
			userMemberInfo.setMembershipFlag(1);
			userMemberInfoDao.updateById(userMemberInfo);
			
		}else {
			//有数据
			userMemberInfo.setId(userMemberInfos.get(0).getId());
			calendar.setTime(new Date(userMemberInfos.get(0).getEndDate()));
			calendar.add(Calendar.YEAR, 1);
			userMemberInfo.setStartDate(null);
			userMemberInfo.setEndDate(calendar.getTime().getTime());
			userMemberInfo.setMembershipFlag(1);
			userMemberInfoDao.updateById(userMemberInfo);										
		}
		DecimalFormat decimalFormat = new DecimalFormat(".00");
		MessageInfo messageInfo = new MessageInfo();
		messageInfo.setTitle("会员开通信息");
		String content = "你的会员套餐（"+ userBalancePayment.getName() +"）购买成功，会员费用为"+decimalFormat.format(userBalancePayment.getMoney()) +"元，会员到期时间为"+DateUtil.longToString(userMemberInfo.getEndDate(), DateUtil.YEAR_MONTH_DAY) + "。";
		messageInfo.setContent(content);
		messageInfo.setSendTime(new Date());
		messageInfo.setSenderId(1);
		messageInfo.setUserId(userInfo.getId());
		messageInfo.setReadTag(0);
		messageInfo.setMsgModule(1);
		messageInfoDao.insert(messageInfo);				
		userInfo.setMemberList(userMemberInfoDao.queryBySelected(userMemberInfo));
		userInfo.setMessageString("ok");
	}
	//付款成功后，新增推广明细记录
	private Map<String,Object> insertPromoteDetail(UserBalancePayment userBalancePayment){
		int count = 0 ;
		Map<String,Object> map = new HashMap<String,Object>();
		//订单金额为0,不插入推广
		if (userBalancePayment.getMoney().compareTo(new Float(0))==0) {
			return null;
		}
        //查询付款人是否是高级推广身份（服务站，合作方，家人等）
        //如果是高级推广身份 则其付款不参与分成
        DistributorInfoDTO payer = distributorInfoDao.queryByUserId(userBalancePayment.getUserId());
        if(payer == null){
        	return null;
        }
		if (SharingProportionEnum.MIDDLE_DISTRIBUTOR.getDistributorType().equals(payer.getDistributorType()) 
        		|| SharingProportionEnum.HIGHT_DISTRIBUTOR.getDistributorType().equals(payer.getDistributorType())
				|| SharingProportionEnum.PARTNER.getDistributorType().equals(payer.getDistributorType()) 
				|| SharingProportionEnum.LECTUER.getDistributorType().equals(payer.getDistributorType())
				|| SharingProportionEnum.MASTER.getDistributorType().equals(payer.getDistributorType()) 
				|| SharingProportionEnum.SERVICE_STATION.getDistributorType().equals(payer.getDistributorType())
				|| SharingProportionEnum.FAMILY.getDistributorType().equals(payer.getDistributorType())) {
			return null;
		}

        PromoteDetailDTO paramDTO = new PromoteDetailDTO();
		paramDTO.setPaymentId(userBalancePayment.getId());
		PromoteDetail info = promoteDetailDao.queryPromoteDetailByPaymentId(paramDTO);
        Integer recommendId = info.getRecommendId();
        String transId = "";//为了发短信用
        String transMoney = "";
        Integer promoterId = null;
        //true-特价  false-非特价
        boolean isSpecial = "1".equals(userBalancePayment.getIsSpecial()) || "2".equals(userBalancePayment.getIsSpecial());
        /**
         * 运营中心--非特价参与分成，特价的和之前的一样
         * 
         */
        if(!isSpecial && info.getRecommendId() != null){//不是特价并且有推广者
        	// 关系链A-->B-->C-->D
        	//先查询推广者是不是运营中心A
        	PromotorLinkDTO pDTO = promotorLinkDao.selectOperationCenterByUserId(userBalancePayment.getUserId()) ; //通过付费者查询其推广关系
        	if(pDTO !=null && "1".equals(pDTO.getIsOperation())){//是运营中心的才拦截操作
        		//1.A-->B B为消费者，A为一级推广
        		if("1".equals(pDTO.getLevel()) && pDTO.getFirstUserId().intValue() ==  pDTO.getOperationUserId()){//推广人id等于运营中心负责人id，则为运营中心直接推广记录
        			info.setRecommendId(pDTO.getFirstUserId());
                    info.setBelongId(pDTO.getFirstUserId());
        			info.setSharingProportion(pDTO.getProportions());
                    info.setDivideMoney(info.getMoney().multiply(new BigDecimal(pDTO.getProportions())).setScale(2, BigDecimal.ROUND_HALF_UP));
                    info.setPromoteType("1");
                    info.setDistributorType(SharingProportionEnum.OPERATION_CENTER.getDistributorType());
                    info.setScanCodeTime(pDTO.getCreateTime());
                    //新增推广的结算推广码
                    info.setProCode(OrderCodeUtil.getOrderCode("prof_", pDTO.getFirstUserId()));
                    info.setOperationCenterId(pDTO.getOperationCenterId());
                    transId += pDTO.getFirstUserId();
                    transMoney += info.getDivideMoney();
                    //及时到账
                    doAutoTransfer(userBalancePayment, info);
                    
                    count = promoteDetailDao.insert(info);
                    if (count == 1) {
                        map.put("err_code", 0);
                        map.put("recommendId", transId);
                        map.put("divideMoney", transMoney);
                    } else {
                        map.put("err_code", 1);
                    }
                    //一定要return，不然会有多笔推广。。
                    return map;
        		}else if("2".equals(pDTO.getLevel())){
					//2.A-->B-->C ，C为付款者，A为运营中心，B为一级推广者，这里的1指的是B，则插入B的一条推广和一条A的推广
					//B的推广
					info.setRecommendId(pDTO.getFirstUserId());
                    info.setBelongId(pDTO.getOperationUserId());
        			info.setSharingProportion(pDTO.getFirstProportions());
                    info.setDivideMoney(info.getMoney().multiply(new BigDecimal(pDTO.getFirstProportions())).setScale(2, BigDecimal.ROUND_HALF_DOWN));
                    info.setPromoteType("1");
                    info.setDistributorType(SharingProportionEnum.OPERATION_CENTER.getDistributorType());
                    info.setScanCodeTime(pDTO.getCreateTime());
                    //新增推广的结算推广码
                    info.setProCode(OrderCodeUtil.getOrderCode("prof_", pDTO.getFirstUserId()));
                    info.setOperationCenterId(pDTO.getOperationCenterId());
                    transId += pDTO.getFirstUserId();
                    transMoney += info.getDivideMoney();
                    //及时到账
                    doAutoTransfer(userBalancePayment, info);
                    //插入B的推广明细
                    promoteDetailDao.insert(info);
                    
                    //A的推广
                    info.setRecommendId(pDTO.getOperationUserId());
                    info.setBelongId(pDTO.getOperationUserId());
        			info.setSharingProportion(pDTO.getSecondProportions());
                    info.setDivideMoney(info.getMoney().multiply(new BigDecimal(pDTO.getSecondProportions())).setScale(2, BigDecimal.ROUND_HALF_DOWN));
                    info.setPromoteType("2");
                    info.setDistributorType(SharingProportionEnum.OPERATION_CENTER.getDistributorType());
                    info.setScanCodeTime(null);
                    //新增推广的结算推广码
                    info.setProCode(OrderCodeUtil.getOrderCode("prof_", pDTO.getOperationUserId()));
                    info.setOperationCenterId(pDTO.getOperationCenterId());
                    transId += "@_@" + pDTO.getOperationUserId();
                    transMoney += "@_@" + info.getDivideMoney();
                    //及时到账
                    doAutoTransfer(userBalancePayment, info);
                    //插入A的推广明细
                    promoteDetailDao.insert(info);
                    
                    map.put("err_code", 0);
                    map.put("recommendId", transId);
                    map.put("divideMoney", transMoney);
                    return map;
				}							
        	}
        }
        
        //查询付款人是否是团队成员（1.6.8.1需求）
        //如果付款人是团队成员，则忽略扫码关系，其团队负责人即是一级推广受益人
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("recommendId", userBalancePayment.getUserId());
        DistributorInfoDTO _teamDTO = distributorInfoDao.queryTeamMemberByUserIdAndCompleteTime(paramMap);
        if (_teamDTO != null) {
            info.setRecommendId(_teamDTO.getBelongTeamId());
            info.setBelongId(_teamDTO.getBelongTeamId());
            info.setRecommendCode(_teamDTO.getShareCode());
			//特价课程包  一级推广10% 二级推广2%
			info.setSharingProportion(isSpecial?0.1:_teamDTO.getSharingProportion());
            info.setDivideMoney(info.getMoney().multiply(new BigDecimal(_teamDTO.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
            info.setPromoteType("4");
            info.setDistributorType(_teamDTO.getDistributorType());
            info.setScanCodeTime(null);
            //新增推广的结算推广码
            info.setProCode(OrderCodeUtil.getOrderCode("prof_", info.getRecommendId()));
            transId += info.getRecommendId();
            transMoney += info.getDivideMoney();
            if (SharingProportionEnum.NORMAL.getDistributorType().equals(_teamDTO.getDistributorType())
            		||SharingProportionEnum.FAMILY.getDistributorType().equals(_teamDTO.getDistributorType())
            		||SharingProportionEnum.SERVICE_STATION.getDistributorType().equals(_teamDTO.getDistributorType())) {
            	doAutoTransfer(userBalancePayment, info);
			}else {
				info.setSettleStatus("0");
			}
            count = promoteDetailDao.insert(info);
            if (count == 1) {
                map.put("err_code", 0);
                map.put("recommendId", transId);
                map.put("divideMoney", transMoney);
                //map.put("distributorType", null);
            } else {
                map.put("err_code", 1);
            }
            return map;
        }

        if (recommendId != null) {
            //1.判断其是否为分销商团员
            paramMap.put("recommendId", info.getRecommendId());
            //paramMap.put("completeTime", info.getCompleteTime());
            DistributorInfoDTO teamDTO = distributorInfoDao.queryTeamMemberByUserIdAndCompleteTime(paramMap);
            if(teamDTO != null){
            	info.setSharingProportion(isSpecial?0.1:teamDTO.getTeamSharingProportion());
                //财务结算给团队成员的分成
                info.setDivideMoney(info.getMoney().multiply(new BigDecimal(info.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
                //标记该分成属于团队成员的
                info.setTeamDivideMoney(info.getDivideMoney());
                info.setBelongId(teamDTO.getBelongTeamId());
                //这个是团队成员的distributor_type
                info.setDistributorType(teamDTO.getDistributorType());
                info.setPromoteType("1");
                //新增推广的结算推广码
                info.setProCode(OrderCodeUtil.getOrderCode("prof_", info.getRecommendId()));
                //处理自动到账,所有团队成员都自动到账
                doAutoTransfer(userBalancePayment, info);
                count = promoteDetailDao.insert(info);//团队--给团队成员的收益
                
                info.setSharingProportion(isSpecial?0.02:new BigDecimal(teamDTO.getSharingProportion() - teamDTO.getTeamSharingProportion()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                //info.setSharingProportion(new BigDecimal(teamDTO.getSharingProportion() - teamDTO.getTeamSharingProportion()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//自己的分成比例-给团队成员设定的分成比例
                info.setDivideMoney(info.getMoney().multiply(new BigDecimal(info.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
                transId += info.getRecommendId() + "@_@" + teamDTO.getBelongTeamId();
                transMoney += info.getTeamDivideMoney() + "@_@" + info.getDivideMoney();
                promoterId = info.getRecommendId();
                info.setSecondPromoterId(info.getRecommendId());
                info.setRecommendId(teamDTO.getBelongTeamId());
                info.setRecommendCode(teamDTO.getShareCode());
                info.setTeamDivideMoney(null);
                info.setPromoteType("3");
                //新增推广的结算推广码
                info.setProCode(OrderCodeUtil.getOrderCode("pros_", info.getRecommendId()));
                
                if (SharingProportionEnum.NORMAL.getDistributorType().equals(info.getDistributorType())
                		||SharingProportionEnum.FAMILY.getDistributorType().equals(info.getDistributorType())
                		||SharingProportionEnum.SERVICE_STATION.getDistributorType().equals(info.getDistributorType())) {
                	doAutoTransfer(userBalancePayment, info);
                }else {//除普通推广者，家人，服务站以外其他推广身份
                	info.setSettleStatus("0");//未结算
                }
                count = promoteDetailDao.insert(info);//团队--给团队负责人的收益
                if (count == 1) {
                    map.put("err_code", 0);
                    map.put("recommendId", transId);
                    map.put("divideMoney", transMoney);
                    //map.put("distributorType", null);
                    map.put("promoterId", promoterId);
				}else{
					map.put("err_code", 1);
				}
				return map;
            }
			//判断直接受益人是否为推广者
			DistributorInfoDTO dit = distributorInfoDao.queryByUserId(info.getRecommendId());
			//不是团队成员,则belong_id就是推荐人的id
			info.setBelongId(info.getRecommendId());
            info.setPromoteType("1");
            if(dit == null){//有可能是其他的角色，没有在推广表里,如学校的推广没有进入到推广明细
				/*//如果有recommendid，但是不属于 哪个推广者
				info.setDivideMoney(info.getMoney().multiply(new BigDecimal(SharingProportionEnum.NORMAL.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
				info.setSharingProportion(SharingProportionEnum.NORMAL.getSharingProportion());
				info.setSettleStatus("0");//未结算
				info.setDistributorType(SharingProportionEnum.NORMAL.getDistributorType());
				count = promoteDetailDao.insert(info);
				transId += info.getRecommendId();
				transMoney += info.getDivideMoney();
				if(count == 1){
					map.put("err_code", 0);
					map.put("recommendId", transId);
					map.put("divideMoney", transMoney);
				}else{
					map.put("err_code", 1);
				}*/
				return null;
			}
			info.setDistributorType(dit.getDistributorType());
			/*
			 * 插入直接受益人的推广明细
			 */
			if(dit.getSharingProportion() != null){
				info.setSharingProportion(isSpecial?0.1:dit.getSharingProportion());
				info.setDivideMoney(info.getMoney().multiply(new BigDecimal(info.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
				//新增推广的结算推广码
				info.setProCode(OrderCodeUtil.getOrderCode("prof_", info.getRecommendId()));
				//处理自动到账
                if (SharingProportionEnum.NORMAL.getDistributorType().equals(dit.getDistributorType())
                		||SharingProportionEnum.FAMILY.getDistributorType().equals(dit.getDistributorType())
                		||SharingProportionEnum.SERVICE_STATION.getDistributorType().equals(dit.getDistributorType())) {
                	doAutoTransfer(userBalancePayment, info);
                }else {//除普通推广者，家人，服务站以外其他推广身份
                	info.setSettleStatus("0");//未结算
                }
            }
            count = promoteDetailDao.insert(info);
            transId += info.getRecommendId();
            transMoney += info.getDivideMoney();
			/**
			 * 如果一级推广是家人，服务站，分销商等话，则没有二级推广记录（他们是顶级推广者）
			 */
            if (SharingProportionEnum.MIDDLE_DISTRIBUTOR.getDistributorType().equals(dit.getDistributorType()) 
            		|| SharingProportionEnum.HIGHT_DISTRIBUTOR.getDistributorType().equals(dit.getDistributorType())
    				|| SharingProportionEnum.PARTNER.getDistributorType().equals(dit.getDistributorType()) 
    				|| SharingProportionEnum.LECTUER.getDistributorType().equals(dit.getDistributorType())
    				|| SharingProportionEnum.MASTER.getDistributorType().equals(dit.getDistributorType()) 
    				|| SharingProportionEnum.SERVICE_STATION.getDistributorType().equals(dit.getDistributorType())
    				|| SharingProportionEnum.FAMILY.getDistributorType().equals(dit.getDistributorType())) {
            	
            	map.put("err_code", 0);
				map.put("recommendId", transId);
				map.put("divideMoney", transMoney);
				map.put("promoterId", info.getRecommendId());
				return map;
    		}
			//新需求:二级分销
			//用recommendId去查,看还有没有上一级推广者
			paramDTO.setUserId(info.getRecommendId());
			PromoteDetail lastPromoter = promoteDetailDao.queryLastPromoterByUserId(paramDTO);
            info.setPromoteType("2");
            info.setSecondPromoterId(info.getRecommendId());
            info.setDataSources("来自二级推广:(直接受益人)" + info.getRecommendId() + "的推广");

            if (null != lastPromoter) {
                lastPromoter.setBelongId(lastPromoter.getRecommendId());
                //判断其是否为分销商团员
                Map<String, Object> _paramMap = new HashMap<String, Object>();
                _paramMap.put("recommendId", lastPromoter.getRecommendId());
                DistributorInfoDTO teamDTO_ = distributorInfoDao.queryTeamMemberByUserIdAndCompleteTime(_paramMap);
                if (teamDTO_ != null) {
                    //是团队成员
                    lastPromoter.setSharingProportion(teamDTO_.getTeamSharingProportion());
                }

				/*
				 * 插入间接受益人的推广明细
				 */
				//判断间接受益人是否为推广者
				DistributorInfoDTO lastDit = distributorInfoDao.queryByUserId(lastPromoter.getRecommendId());
				//如果有recommendid，但是不属于 哪个推广者
				if(lastDit == null){//有可能是其他的角色，没有在推广表里
					info.setDivideMoney(info.getMoney().multiply(new BigDecimal(GlobalConstant.SECOND_PROMOTE_PROPORTION)).multiply(new BigDecimal(SharingProportionEnum.NORMAL.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
					info.setSharingProportion(Math.round(SharingProportionEnum.NORMAL.getSharingProportion()*GlobalConstant.SECOND_PROMOTE_PROPORTION  * 100) * 0.01d);
					info.setSettleStatus("0");//未结算
					transId += "@_@"+lastPromoter.getRecommendId();
					transMoney += "@_@"+info.getDivideMoney();
					promoterId = info.getRecommendId();
					info.setRecommendId(lastPromoter.getRecommendId());
					info.setRecommendCode(lastPromoter.getRecommendCode());
					info.setBelongId(lastPromoter.getRecommendId());
					//新增推广的结算推广码
					info.setProCode(OrderCodeUtil.getOrderCode("pros_", info.getRecommendId()));
					count = promoteDetailDao.insert(info);
					if(count == 1){
						map.put("err_code", 0);
						map.put("recommendId", transId);
						map.put("divideMoney", transMoney);
						map.put("promoterId", promoterId);
					}else{
						map.put("err_code", 1);
					}
					return map;
				}
				info.setDistributorType(lastDit.getDistributorType());
				lastPromoter.setSharingProportion(isSpecial?0.02:Math.round(lastPromoter.getSharingProportion() * GlobalConstant.SECOND_PROMOTE_PROPORTION * 100) * 0.01d);
				lastPromoter.setDivideMoney(info.getMoney().multiply(new BigDecimal(lastPromoter.getSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP));
				lastPromoter.setProCode(OrderCodeUtil.getOrderCode("pros_", lastPromoter.getRecommendId()));
				if (SharingProportionEnum.NORMAL.getDistributorType().equals(lastDit.getDistributorType())
                		||SharingProportionEnum.FAMILY.getDistributorType().equals(lastDit.getDistributorType())
                		||SharingProportionEnum.SERVICE_STATION.getDistributorType().equals(lastDit.getDistributorType())) {
                	//处理自动到账
	                doAutoTransfer(userBalancePayment, lastPromoter);
	                info.setSettleStatus(lastPromoter.getSettleStatus());
                }else {//除普通推广者，家人，服务站以外其他推广身份
                	info.setSettleStatus("0");//未结算
                }

                //二级分销中,间接受益人只获得其分成比例1/5的分成
                info.setDivideMoney(lastPromoter.getDivideMoney());
                info.setSharingProportion(lastPromoter.getSharingProportion());
                //info.setSharingProportion(Math.round(lastPromoter.getSharingProportion() * GlobalConstant.SECOND_PROMOTE_PROPORTION * 100) * 0.01d);
                info.setRecommendCode(lastPromoter.getRecommendCode());
                promoterId = info.getRecommendId();
				info.setRecommendId(lastPromoter.getRecommendId());
				info.setBelongId(lastPromoter.getRecommendId());
				//新增推广的结算推广码
				info.setProCode(lastPromoter.getProCode());
				count = promoteDetailDao.insert(info);
				transId += "@_@"+info.getRecommendId();
				transMoney += "@_@"+info.getDivideMoney();
			}

			if(count == 1){
				map.put("err_code", 0);
				map.put("recommendId", transId);
				map.put("divideMoney", transMoney);
				map.put("promoterId", promoterId);
			}else{
				map.put("err_code", 1);
			}
			return map;
		}
		return null;
	}
	
	private void doAutoTransfer(UserBalancePayment payment,PromoteDetail info){
		//判断当前时间是否为06:00-23:00，如果是，直接及时到账，否则就早上6点钟定时器转账
		if(DateUtil.betweenTime()){
			//企业付款零钱到推广者微信账户
			TransferInfo transInfo = new TransferInfo();
			transInfo.setAmount(info.getDivideMoney());
			transInfo.setPartnerTradeNo(info.getProCode().replaceAll("_", ""));
            transInfo.setUserId(info.getRecommendId());
            transInfo.setPaymentDesc("会员或课程推广成功分成收入");
            @SuppressWarnings("unchecked")
            Map<String, Object> returnMap = (Map<String, Object>) transferPaymentBo.weChatTransferPay(transInfo);
            int row = 0;
            if(returnMap != null ){
				if("200".equals(returnMap.get("err_code"))){//付款成功
					transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
					transInfo.setCompleteTime(Timestamp.valueOf((String) returnMap.get("paymentTime")));
					transInfo.setDisabledFlag("0");
					transInfo.setTransferStatus("1");
					transInfo.setErrCode((String) returnMap.get("err_code"));
					transInfo.setErrCodeDes((String) returnMap.get("err_code_des"));
					transInfo.setPaymentId(payment.getId());
					row = transferInfoDao.insert(transInfo);
					if(row == 1){
						info.setSettleStatus("1");//已结算
					}
				}else{//付款失败
					transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
					transInfo.setDisabledFlag("0");
					transInfo.setTransferStatus("0");
					transInfo.setErrCode((String) returnMap.get("err_code"));
					transInfo.setErrCodeDes((String) returnMap.get("err_code_des"));
					transInfo.setPaymentId(payment.getId());
					row = transferInfoDao.insert(transInfo);
					if(row == 1){
						info.setSettleStatus("0");//未结算
					}
				}
			}else {
				transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
				transInfo.setDisabledFlag("0");
				transInfo.setTransferStatus("0");
				transInfo.setErrCode("100");
				transInfo.setErrCodeDes("企业付款时没有返回map");
				transInfo.setPaymentId(payment.getId());
				row = transferInfoDao.insert(transInfo);
				if(row == 1){
					info.setSettleStatus("0");//未结算
				}
			}
		}else{
			info.setSettleStatus("0");//未结算
		}
	}
	
	/*@Override
	public Object getScanPayUrl(OrderInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == info || StringUtils.isBlank(info.getCode())){
			map.put("err_code", -1);
			map.put("err_msg", "传入用户信息不存在");
			return map;
		}
//		
//		String appId = Configure.getAppid();
//		String macId = Configure.getMchid();
//		String productId = info.getCode();
//		//随机字符串
//		String noncestr = UUID.randomUUID().toString();
//		//时间戳
//        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        
        
        ScanPayReqData scanPayReqData = new ScanPayReqData();
        scanPayReqData.setAppid(Configure.getAppid());
        scanPayReqData.setMch_id(Configure.getAppid());
        scanPayReqData.setProduct_id(info.getCode());
        scanPayReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
        scanPayReqData.setTimestamp(Long.toString(System.currentTimeMillis() / 1000));
        scanPayReqData.setSign(Signature.getSign(scanPayReqData.toMap()));
        
		String scanPayUrl = WxConsts.getWeChatApiURL(WxConsts.GET_SCANPAY_URL,
				scanPayReqData.getSign(),
				scanPayReqData.getAppid(),
				scanPayReqData.getMch_id(),
				scanPayReqData.getProduct_id(),
				scanPayReqData.getTimestamp(),
				scanPayReqData.getNonce_str());
		if(StringUtils.isNotBlank(scanPayUrl)){
			map.put("err_code", 0);
			map.put("err_msg", "获取成功");
			map.put("scanPayUrl", scanPayUrl);
		}else{
			map.put("err_code", -2);
			map.put("err_msg", "获取失败");
			map.put("scanPayUrl", null);
		}
		
		return map;
	}*/

	@Override
	public Object getScanPayUrl(OrderInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == info || StringUtils.isBlank(info.getCode())){
			map.put("err_code", -1);
			map.put("err_msg", "传入用户信息不存在");
			return map;
		}
//		
//		String appId = Configure.getAppid();
//		String macId = Configure.getMchid();
//		String productId = info.getCode();
//		//随机字符串
//		String noncestr = UUID.randomUUID().toString();
//		//时间戳
//        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        
        
        ScanPayReqData scanPayReqData = new ScanPayReqData();
        scanPayReqData.setAppid(Configure.getAppid());
        scanPayReqData.setMch_id(Configure.getAppid());
        scanPayReqData.setProduct_id(info.getCode());
        scanPayReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
        scanPayReqData.setTimestamp(Long.toString(System.currentTimeMillis() / 1000));
        scanPayReqData.setSign(Signature.getSign(scanPayReqData.toMap()));
        
		String scanPayUrl = WxConsts.getWeChatApiURL(WxConsts.GET_SCANPAY_URL,
				scanPayReqData.getSign(),
				scanPayReqData.getAppid(),
				scanPayReqData.getMch_id(),
				scanPayReqData.getProduct_id(),
				scanPayReqData.getTimestamp(),
				scanPayReqData.getNonce_str());
		if(StringUtils.isNotBlank(scanPayUrl)){
			map.put("err_code", 0);
			map.put("err_msg", "获取成功");
			map.put("scanPayUrl", scanPayUrl);
		}else{
			map.put("err_code", -2);
			map.put("err_msg", "获取失败");
			map.put("scanPayUrl", null);
		}
		
		return map;
	}

	@Override
	public Object querySchoolStudentPaymentBySchoolId(UserBalancePaymentSchoolDTO dto , UserInfo ui) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(ui == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户登录失效");
			return map;
		}
		if(ui.getRoleId().intValue() == RoleInfoEnum.SCHOOL_ADMIN.getRoleId() 
				|| ui.getRoleId().intValue() == RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId()){//学校管理员
			dto.setSchoolId(ui.getSchoolId());
		}


        UserBalancePaymentSchoolTotalDTO totalDTO = userBalancePaymentDao.queryTotalSchoolStudentPaymentBySchoolId(dto);
        Integer totalPayment = 0;
		Integer totalSchool = 0;
		Float totalMoney = 0.0f; 
		if(totalDTO != null){
			totalPayment = totalDTO.getTotalPayment();
			totalSchool = totalDTO.getTotalSchool();
			totalMoney = totalDTO.getTotalMoney();
		}
		int count = userBalancePaymentDao.queryCountSchoolStudentPaymentBySchoolId(dto);
		if(count > 0){
			List<UserBalancePaymentSchoolDTO> list = userBalancePaymentDao.querySchoolStudentPaymentBySchoolId(dto);
			if(list != null && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功，有数据");
				map.put("rows", list);
				map.put("total", count);
				map.put("totalPayment", totalPayment);
				map.put("totalSchool", totalSchool);
				map.put("totalMoney", totalMoney);
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "无数据");
				map.put("rows", list);
				map.put("total", count);
				map.put("totalPayment", totalPayment);
				map.put("totalSchool", totalSchool);
				map.put("totalMoney", totalMoney);
			}
			
		}else{
			map.put("err_code", 2);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("total", count);
			map.put("totalPayment", totalPayment);
			map.put("totalSchool", totalSchool);
			map.put("totalMoney", totalMoney);
		}
		return map;
	}


	@Override
	public Object exportExl(UserBalancePayment userBalancePayment,
			HttpServletResponse response,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<UserBalancePayment> dataset = userBalancePaymentDao.queryPaymentByPage(userBalancePayment);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
	    for (UserBalancePayment payment : dataset) {
			if (StringUtils.isNotBlank(payment.getSettleStatus())) {
				if (payment.getSettleStatus().equals("0")) {
					payment.setSettleStatus("待结");
				}
				if (payment.getSettleStatus().equals("1")) {
					payment.setSettleStatus("已结");
				}
			}
		}
		try {
			ExcelUtil.writeExcel(response, "订单"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, UserBalancePayment.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}


	@Override
	public Object exportSchoolUserPaymentBack(HttpServletResponse response,UserBalancePaymentSchoolDTO dto, UserInfo ui) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(ui == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户没有登录或登录失效！");
			return map ;
		}else{
			
			List<UserBalancePaymentSchoolDTO> list = userBalancePaymentDao.querySchoolStudentPaymentBySchoolId(dto);
			if(list != null && list.size() > 0){
				String fileName =  "校园推广" + DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR) + ".xls";
				try {
					ExcelUtil.writeExcel(response, fileName, list, UserBalancePaymentSchoolDTO.class);
					map.put("err_code", 200);
					map.put("err_msg", "成功");
				} catch (IllegalArgumentException | IllegalAccessException
						| IOException e) {
					e.printStackTrace();
				}
			}else{
					map.put("err_code", 404);
					map.put("err_msg", "无可导出数据");
					
			}
			return map;
		}
	}

	@Override
	public Object txUpdateOrderNote(UserBalancePayment userBalancePayment) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (userBalancePayment.getId()==null) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选一条记录");
			return map;
		}
		int row = userBalancePaymentDao.updatePayment(userBalancePayment);
		if (row>0) {
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", -1);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public Object isDuringActivity(UserBalancePayment userBalancePayment,
			Map<String, Object> map) {
		//活动2017-12-28 00:00:00 - 2017-12-29 00:00:00 
		if(1514390400000l > System.currentTimeMillis() || System.currentTimeMillis() > 1514563199000l){
			map.put("err_code", -1);
			map.put("err_msg", "还未到活动时间");
			return map;
		}
		UserBalancePayment balancePayment = userBalancePaymentDao.isDuringActivity(userBalancePayment);
		if(null == balancePayment){
			map.put("err_code", 200);
			map.put("err_msg", "该用户可参与活动优惠");
			return map;
		}else{
			map.put("err_code", 400);
			map.put("err_msg", "该用户已经参与活动优惠");
			return map;
		}
	}

	@Override
	public Object groupByMoney() {
		return userBalancePaymentDao.groupByMoney();
	}

	@Override
	public Object querySpecialPayment(UserBalancePayment userBalancePayment,
			HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (loginUser.getRoleId()==2) {
			//老师只能看自己的
			userBalancePayment.setTeacherId(loginUser.getId());
		}
		UserBalancePaymentDto dto = userBalancePaymentDao.countSpecialPayment(userBalancePayment);
		List<SpecialPaymentDTO> list = null;
		if (dto.getTotalPaid() > 0) {
			list = userBalancePaymentDao.querySpecialPayment(userBalancePayment);
		}
		map.put("err_code", 200);
		map.put("err_msg", "查询成功");
		map.put("rows", list);
		map.put("total", dto.getTotalPaid());
		map.put("totalCourse", dto.getTotalCourse());
		map.put("totalTeacher", dto.getTotalTeacher());
		map.put("totalPaidMoney", dto.getTotalPaidMoney());
		return map;
	}

	@Override
	public Object exportSpecialPayment(UserBalancePayment userBalancePayment,
			HttpServletResponse response, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser ){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		List<SpecialPaymentDTO> dataset = userBalancePaymentDao.querySpecialPayment(userBalancePayment);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "特价课程"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, SpecialPaymentDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

}
